Java > String-1 > extraFront (CodingBat Solution)

Problem:

Given a string, return a new string made of 3 copies of the first 2 chars of the original string. The string may be any length. If there are fewer than 2 chars, use whatever is there.

extraFront("Hello") → "HeHeHe"
extraFront("ab") → "ababab"
extraFront("H") → "HHH"


Solution:

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


3 comments :

  1. public String extraFront(String str) {
    if(str.length()<2)
    return str+str+str;
    else return str.substring(0,2)+str.substring(0,2)+str.substring(0,2);
    }

    ReplyDelete
  2. public String extraFront(String str) {
    if(str.length() > 2)
    str=str.substring(0,2);

    return str+str+str;
    }

    ReplyDelete
  3. public String extraFront(String str) {
    String front = (str.length() <= 2)? str: str.substring(0, 2);
    return front + front + front;
    }

    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