Java > String-1 > right2 (CodingBat Solution)

Problem:

Given a string, return a "rotated right 2" version where the last 2 chars are moved to the start. The string length will be at least 2.

right2("Hello") → "loHel"
right2("java") → "vaja"
right2("Hi") → "Hi"


Solution:

public String right2(String str) {
  return str.substring(str.length()-2, str.length()) + str.substring(0,  
    str.length()-2);
}


3 comments :

  1. public String right2(String str) {
    if(str.length() <= 2){
    return str;
    }
    final String lastTwoChar = str.substring(Math.max(0, str.length() - 2));
    if(str.length() < 4){
    return str.substring(1) + str.charAt(0);
    }
    return lastTwoChar + str.substring(0, str.length()- 2);
    }

    ReplyDelete
  2. public String right2(String str) {

    String lastTwo = str.substring(str.length()-2);



    return lastTwo + str.substring(0, str.length()-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