Ryan
Ryan

Reputation: 67

How do you reverse a string character by character in java?

Let's say I have a string with the phrase "Bank of America". I want to reverse it so the output results in "aciremA fo knaB"

This is the code I have been trying to use but the output is only the last letter of the last word, which would be "a"

int position = phraseLength;
for(int index = position-1; index >= 0; index--);
System.out.println(p1.charAt(position-1));

I am not sure what is wrong here so any help would be appericated.

Upvotes: 0

Views: 343

Answers (6)

Levi Richards
Levi Richards

Reputation: 1

Declare a string. Take out the length of that string. Loop through the characters of the string. Add the characters in reverse order in the new string. String str = "hello";

String reverse = "";

int length = str.length();

for (int i = 0; i < length; i++) {

 reverse = str.charAt(i) + reverse;

}

System.out.println(reverse);

Upvotes: 0

AndrewLove8
AndrewLove8

Reputation: 1

StringBuffer stringBuffer=new StringBuffer("Bank of America");
System.out.println(stringBuffer.reverse());    

Upvotes: 0

PVR
PVR

Reputation: 2524

I guess by mistake you have added the semicolon after for loop. Practically this will not give any compile time error. But the content of the loop will be executed only once. So remove the semicolon and get it done !!

Upvotes: 0

Android Noob
Android Noob

Reputation: 3341

public String reverse(String str) {   
 char [] buffer = str.toCharArray();

 for (int i = 0, j = buffer.length - 1; i < j; i++, j--) {
  char temp = buffer[i];
  buffer[i] = buffer[j];
  buffer[j] = temp;
 }

 return new String(buffer);
}

Upvotes: 0

stinepike
stinepike

Reputation: 54742

You have added an extra semicolon after for loop here

for(int index = position-1; index >= 0; index--);
                                                ^

Also you are always accessing the postion-i. You should access the index

System.out.println(p1.charAt(position-1));
                             ^^^^^^^^^^^
                                here

You can use this

int position = phraseLength;
for(int index = position-1; index >= 0; index--)
    System.out.print(p1.charAt(index));

or this

String output = "";
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
    output+=p1.charAt(index);
System.out.println(output);

Upvotes: 3

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

    StringBuffer sb=new StringBuffer("Bank of America");
    System.out.println(sb.reverse());

If you want to do it your way. use

    int position = phraseLength;
    for(int index = position-1; index >= 0; index--)
        System.out.println(p1.charAt(index));

Upvotes: 4

Related Questions