user8887707
user8887707

Reputation:

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!

Upvotes: 1

Views: 1236

Answers (4)

AliOmar62
AliOmar62

Reputation: 55

Use this code to do it manually.

public class Reverse {
public static void main(String args []) {
    String rev = "This should be reversed";
    StringBuilder stb = new StringBuilder();
    int i = rev.length()-1;
    while (i != -1) {
            char re = rev.charAt(i);
            stb.append(re);
            i--;
        }
        System.out.println(stb);
    }
}

Upvotes: 0

romph
romph

Reputation: 487

swap it two by two if you arent allowed to use reverse() method

StringBuilder sb = new StringBuilder("abcde");
for (int i = 0; i < sb.length()/2; i++) {
    char tmp = sb.charAt(i);
    sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
    sb.setCharAt(sb.length() - 1 - i, tmp);
}
System.out.println(sb.toString());

Upvotes: 0

parsa
parsa

Reputation: 985

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);
}

Upvotes: 1

parsa
parsa

Reputation: 985

if you want to reverse your string why dont you use

StringBuilder str = new StringBuilder();
str.append("yourstring");
str.reverse();

Upvotes: 1

Related Questions