HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Reverse last 2 chars of a String

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
laststringreversechars

Problem

I have this problem:
Given a String of any length, return a new String where the last 2 chars, if present, are swapped. My question is, is there a more delicate way to do this than this way:

public String lastTwo(String str) {
   if(str.length() < 2 || str.equals("")){
      return str;
   }
   String lastTwo = str.substring(str.length() - 2);
   StringBuilder sb = new StringBuilder(lastTwo);
   String lastTwoReversed = sb.reverse().toString();
   return str.substring(0, str.length() - 2) + lastTwoReversed;
}

Solution

Rather than generating the substring for the last two chars and reversing it, you could simply add the last two chars in reverse order:

return str.substring(0, str.length() - 2)
    + str.charAt(str.length() - 1)
    + str.charAt(str.length() - 2);

Code Snippets

return str.substring(0, str.length() - 2)
    + str.charAt(str.length() - 1)
    + str.charAt(str.length() - 2);

Context

StackExchange Code Review Q#113393, answer score: 14

Revisions (0)

No revisions yet.