Java > String-1 > lastTwo (CodingBat Solution)

Problem:

Given a string of any length, return a new string where the last 2 chars, if present, are swapped, so "coding" yields "codign".

lastTwo("coding") → "codign"
lastTwo("cat") → "cta"
lastTwo("ab") → "ba"


Solution:

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


6 comments :

  1. The blog helps me to to improve my knowledge in the latest technology. Thank you admin

    Simple Truth

    Article submission sites

    ReplyDelete
  2. public String lastTwo(String str) {
    return str.length()>1?str.substring(0,str.length()-2)+str.substring(str.length()-1)+str.substring(str.length()-2,str.length()-2+1):str;
    }

    ReplyDelete
  3. public String lastTwo(String str) {
    if(str.length()>=2){
    String a=str.substring(0,str.length()-2);
    String b=str.substring(str.length()-2,str.length()-1);
    String c=str.substring(str.length()-1,str.length());
    return a+c+b;
    }
    if(str.length()<2){
    return str;
    }return str;

    }

    ReplyDelete
  4. public String lastTwo(String str) {

    while (str.length() >= 2){
    String a = str.substring(0, str.length() - 2);
    String b = str.substring(str.length() - 2, str.length() - 1);
    String c = str.substring(str.length() - 1, str.length());
    return a + c + b;
    }
    return str;

    }

    ReplyDelete
  5. function lastTwo(str){
    let beforeLastChar = str.substring(str.length - 1, str.length - 2);
    let lastChar = str.substring(str.length - 1);
    str = str.substring(0, str.length - 2)
    return str + lastChar + beforeLastChar;
    }

    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