Java > Warmup-1 > front3 (CodingBat Solution)

Problem:

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

front3("Java") → "JavJavJav"
front3("Chocolate") → "ChoChoCho"
front3("abc") → "abcabcabc"


Solution:

public String front3(String str) {
  if (str.length() <= 3)
    return str + str + str;
  else {
    String newString = str.substring(0,3); 
    return newString + newString + newString;
  }
}


1 comment :

  1. public String front3(String str) {
    final String front3 = (str.length() <= 3)? str: str.substring(0, 3);
    return front3 + front3 + front3;
    }

    ReplyDelete

Follow Me

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

Subscribe

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?

Upload

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