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


2 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

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