Swapping the first and the last letter of a string in Java? -


int length = s.length();  if (length <= 1){     return s; }  else {      return s.charat(length) + s.substring(1, length-1) + s.charat(0);  } 

i'm trying swap first letter , last letter of string.

eg. apple -> eppla

it compiled fine , works fine empty string or string 1 character only. strings several characters, says:

stringindexoutofboundsexception occured - see console stack trace 

does tht mean there's wrong code???

try this:

int length = s.length();  if (length <= 1) {     return s; } else {     return s.charat(length - 1) + s.substring(1, length - 1) + s.charat(0); } 

the difference s.charat(length - 1). remember, string zero-indexed, last character s.charat(length - 1).


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -