Jim Vekemans
Jim Vekemans

Reputation: 51

Sentence reverse in java

So i'm trying to reverse a sentence and even though I don't have any errors when compiling, it tells me my reverse sentence is out of bounds.

-It should work like this: "hello, world!" --> !dlrow ,olleh"

Said code:

    String sentence="this is a sentence!";
    String reverseSentence=sentence;
    for(int counter=0;counter<sentence.length();counter++)
    {
        char charToReplace,replaceChar;

        charToReplace = reverseSentence.charAt(counter);
        replaceChar = sentence.charAt(sentence.length()-counter);

        reverseSentence=reverseSentence.replace(charToReplace, replaceChar);

        System.out.println(reverseSentence);
    }

Upvotes: 1

Views: 238

Answers (5)

The Law
The Law

Reputation: 334

Just split the String at each whitespace and put it in String array and then print the array in reverse order

    public static void main(String[] args) {
    String sentence = "this is a sentence!";
    String[] reverseSentence = sentence.split(" ");

      for (int i = reverseSentence.length-1; i >= 0; i--) {
        System.out.print(" " + reverseSentence[i]);
      }

    }

Upvotes: 0

robjwilkins
robjwilkins

Reputation: 5652

It maybe better to do it without any replacement, or for loop. It you create a char array from the string, reverse the array, then create a string from the reversed array this would do what you've asked without any moving parts or replacements. For example:

    String hw = "hello world";
    char[] hwChars = hw.toCharArray();
    ArrayUtils.reverse(hwChars);
    String wh = new String(hwChars);
    System.out.println(wh);

Upvotes: 0

Yassin Hajaj
Yassin Hajaj

Reputation: 21995

It doesn't show you an error because the Exception concerning the indexes happen at RunTime.

Here :

replaceChar = sentence.charAt(sentence.length()-counter);

You're trying to access index 19 of your String (19-0). Replace it with :

replaceChar = sentence.charAt(sentence.length()-counter-1);

I'd recommend to use a StringBuilder in your situation though.

Either use the reverse() method :

String sentence = "this is a sentence!";
String reversed = new StringBuilder(sentence).reverse().toString();
System.out.println(reversed); // Prints : !ecnetnes a si siht

Or use the append() method for building your new String object. This uses less memory than using a String because it is not creating a new String object each time you're looping :

String sentence = "this is a sentence!";
StringBuilder reversed = new StringBuilder();

for (int i = 0 ; i < sentence.length() ; i++){
    reversed.append(sentence.charAt(sentence.length() - 1 - i));
}

System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht

Upvotes: 1

ccc
ccc

Reputation: 370

You can use character arrays to implement your requirement like this,

    String sentence = "ABDEF";
    char[] firstString = sentence.toCharArray();
    char[] reversedString = new char[sentence.length()];

    for (int counter = 0; counter < sentence.length(); counter++) {
        reversedString[counter] = firstString[sentence.length() - counter -1];
    }
    System.out.println(String.copyValueOf(reversedString));

Upvotes: 1

Eran
Eran

Reputation: 393936

The reason for the exception you are getting is that in sentence.charAt(sentence.length()-counter), sentence.length()-counter is out of bounds when counter is 0. Should be sentence.length()-1-counter.

However, as Tunaki commented, there are other problems with your code. I suggest you use a StringBuilder to construct the reversed String, instead of using replace (which would replace any occurrence of the first character with the second character).

Upvotes: 2

Related Questions