1

I am a beginner of Java, and would like to reverse the character order of a sentence when I input some words as command line arguments.

Here is my code. When I input "This is a pen.", the output should be ".nep a si sihT". However, the output of this code is ".nep a si sihT ". It includes an extra space at the end of the reversed sentence.

Does anyone know how can I delete the space?

public class Reverse {
    public static void main(String[] args){
        for(int i = args.length - 1; i >= 0; i--){
            for(int j = args[i].length() - 1; j >= 0; j--){
                System.out.print(args[i].charAt(j));
            }
            System.out.print(" ");
        }
    }
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
satohh
  • 45
  • 4
  • 1
    Does this answer your question? [Reverse a string in Java](https://stackoverflow.com/questions/7569335/reverse-a-string-in-java) – Kai-Sheng Yang May 14 '22 at 15:35
  • This is effectively just an instance of [joining an array (of reversed strings) with a separator (space)](https://stackoverflow.com/questions/1978933/a-quick-and-easy-way-to-join-array-elements-with-a-separator-the-opposite-of-sp) – Luatic May 14 '22 at 15:49

2 Answers2

2

If you're sure that leading and trailing spaces are inconsequential to your subsequent logic, you can just apply the function trim() to your result.

trim() doesn't affect middle spaces, so the rest of your logic should still pan out fine.

You can also save your string in a variable and print it out just once - at the end of your logic. All in all, your logic would look like this:

public class Reverse {
    public static void main(String[] args){
        String res = "";
        for(int i = args.length - 1; i >= 0; i--){
            for(int j = args[i].length() - 1; j >= 0; j--){
                res += args[i].charAt(j);
            }
            res += " ";
        }
        System.out.print(res.trim());
    }
}
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
1

Avoid space at end by adding a if statement which skips last iteration

public class Reverse {
    public static void main(String[] args){
        for(int i = args.length - 1; i >= 0; i--){
            for(int j = args[i].length() - 1; j >= 0; j--){
                System.out.print(args[i].charAt(j));
            }
            if(i != 0){
                System.out.print(" ");
            }
        }
    }
}
THUNDER 07
  • 521
  • 5
  • 21