Java > String-1 > nTwice (CodingBat Solution)


Given a string and an int n, return a string made of the first and last n chars from the string. The string length will be at least n.

nTwice("Hello", 2) → "Helo"
nTwice("Chocolate", 3) → "Choate"
nTwice("Chocolate", 1) → "Ce"


public String nTwice(String str, int n) {
  return str.substring(0,n) + str.substring(str.length()- n, str.length());

1 comment :

  1. public String nTwice(String str, int n) {
    return str.substring(0,n).concat(str.substring(str.length()-n));


Follow Me

If you like our content, feel free to follow me to stay updated.


Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?


Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact