Java > String-1 > extraEnd (CodingBat Solution)

Problem:

Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.

extraEnd("Hello") → "lololo"
extraEnd("ab") → "ababab"
extraEnd("Hi") → "HiHiHi"


Solution:

public String extraEnd(String str) {
  String s = str.substring(str.length()-2, str.length());
  return s+s+s;
}


6 comments :

  1. public String extraEnd(String str) {
    if(str.length()<2)
    {
    return str;
    }
    String end = str.substring(str.length()-2,str.length());
    return end+end+end;
    }

    ReplyDelete
  2. public String extraEnd(String str) {
    final String lastTwo = "" + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
    return lastTwo + lastTwo + lastTwo ;
    }

    ReplyDelete
  3. public String extraEnd(String str) {
    String res="";
    String m=str.substring(str.length()-2,str.length());
    if(str.length()==2)
    return res=str+str+str;
    else
    return res=m+m+m;
    }

    ReplyDelete
  4. public String extraEnd(String str) {
    String penultimate = str.substring(str.length() - 2);
    String last = str.substring(str.length());
    String sumReiteration = penultimate + last;
    return sumReiteration + sumReiteration + sumReiteration;
    }

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

    ReplyDelete
  6. public String extraEnd(String str) {
    String ans ;
    int s2 = str.length();
    String s1 = str.substring(s2-2,s2);
    ans = s1+s1+s1;
    return ans;
    }

    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