Search code examples
javastringstringbuffer

How to transfer the last character of a StringBuffer to the beginning?


I'm trying to transfer the last character of a StringBuffer to the beginning by using StringBuffer.insert(). I want to be able to do this even if I don't know the word in advance.

I tried to transfer the letter using the insert() and length() methods below, but it did not work.

    StringBuffer str3 = new StringBuffer("Colour");
    System.out.println(str3.insert(0,str3.length()));

    // output is "6Colour"

Solution

  • When you insert str3.Length() at position 0 you're inserting the length, as an int, at that position instead of the last character of str3.

    Try the below code to insert the character instead:

    StringBuffer str3 = new StringBuffer("Colour");
    
    char lastChar = str3.charAt(str3.length()- 1);
    
    System.out.println(str3.insert(0, lastChar));
    

    You might find this article helpful to learn more about StringBuffer.Insert().

    Edit:

    As @Nexevis mentioned if you want to remove the StringBuffer's last character this answer says you can do this: str3.setLength(Math.max(str3.length() - 1, 0)); to remove it.

    This Math.max() ensures that .setLength() won't set the length to be a negative number if the string size is 0.