Question

I'm trying to remove all the spaces in a string using replaceAll(" ", "") but any text such as "hello world" will remove not only the spaces but the text after the space -- what I mean is that I end up with with just "hello" instead of "helloworld". What am I doing wrong?

public static void main (String [] args) {
            String input;
            Scanner console = new Scanner(System.in);

            System.out.print("enter text: ");
            input = console.next();
            System.out.println();

            input.replaceAll(" ", "");
            System.out.println(input);
    }
Was it helpful?

Solution

You have to reassign it to your variable (or to a new one):

input = input.replaceAll(" ", "");

Strings are immutable which means they cannot be altered. What replaceAll() does is create a new string. Therefore in order to use it, you have to assign it to a variable.

The reason you are only seeing Hello is because you're using scanner.next() instead of scanner.nextLine().

The former will only take the first token until the delimiter (standard: whitespace) is reached. The latter will consider an endline character (in windows: \r\n, enter) as its delimiter.

Your working code looks like this:

public static void main (String [] args) {
        String input;
        Scanner console = new Scanner(System.in);

        System.out.print("enter text: ");
        input = console.nextLine(); // Change here
        System.out.println();

        input = input.replaceAll(" ", ""); // Change here
        System.out.println(input);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top