Home > front end >  My reverse a string code includes a space at the end of the string
My reverse a string code includes a space at the end of the string

Time:05-15

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

CodePudding user response:

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

CodePudding user response:

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(" ");
            }
        }
    }
}
  •  Tags:  
  • java
  • Related