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;
  }
}


8 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
  4. public String extraFront(String str) {
    if(str.length()>=2){
    String a=str.substring(0,2);
    return a+a+a;
    }if(str.length()<2 && str.length()>0){
    String a=str.substring(0,1);
    return a+a+a;
    }else return "";

    }

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

    ReplyDelete
  6. public String extraFront(String str) {
    if (str.length()>2){
    return str.substring(0,2)+str.substring(0,2)+str.substring(0,2) ;
    }
    else
    return str + str + str;

    }

    ReplyDelete
  7. public String extraFront(String str) {

    String res = str.substring(0,Math.min(str.length(),2));
    return res+res+res;
    }

    ReplyDelete
  8. Another way

    public String extraFront(String str) {
    if (str.length() < 2) return String.join("", Collections.nCopies(3, str
    ));
    return String.join("", Collections.nCopies(3, str.substring(0, 2)));
    }

    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