Search code examples
javaappendstringbuildercharat

Problems with stringBuilder.append().charAt in Java


I know that it exists, but my teacher wants me to do it manuallyI am trying to reverse my a stringBuilder so that the characters I have inside go in reverse order, sometimes the stringBuilder is of a single character, that is why as you can see there is an if that indicates when the characters of the stringBuilder should be turned over. This is what I have at the moment.

if ( sB.length ()> 1) {
    for (int i = sB.length () - 1; i> = 0; i--) {
        sB.append().charAt(i);
        sB.deleteCharAt (i); 
    }
}

I know sB.reverse() exists, but my teacher wants me to do it manually and how you can see i don't know how to implement this two method's at once. If anyone can help me please. Thanks!


Solution

  • then in that case use this

    StringBuilder str = new StringBuilder();
    str.append("yourstring");
    for(int i = str.length()-1 ; i>=0; i--)
    {
        str.append(str.charAt(i)).deleteCharAt(i);
    }