Skip to content
Advertisement

My reverse a string code includes a space at the end of the string

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

Advertisement

Answer

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(" ");
            }
        }
    }
}
Advertisement