Adrian
Adrian

Reputation: 300

I need to remove the spaces from a string input from console

so I have a console input in this format:

"Adrian, 18, 180, 80" And I used this which doesn't work

BufferedReader reader = new BufferedReader(newInputStreamReader(System.in));
line = reader.readLine();
System.out.println("You added this user: " + line);
String[] b=line.split(",");
for(String name : b){
   name.replace(" ","");
   System.out.println(name);
   }

However, the output is the following:

Adi
 16
 180
 80

I have tried different methods but no one seems to work for me. Maybe it could be because I call it there into the for loop

Upvotes: 1

Views: 345

Answers (5)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10366

String is immutable, so when you call replace, you are not actually removing spaces from name, but just creating a new string with no reference to it. You can simply assign the replace return to name:

for (String name : b) {
   name = name.replace(" ","");
   System.out.print(name);
}

Furthermore, if you want to have the output in a single line, you should use System.out.print instead of System.out.println (as above). The latter adds a newline at the end of the input.

Upvotes: 1

Philip Z.
Philip Z.

Reputation: 226

Taking a look at the documentation of the String.replace() method we find the following: "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."

This means you have to save the result of name.replace(" ","") because the method doesn't change your old string. Try this:

name = name.replace(" ","");

Upvotes: 1

Ruelos Joel
Ruelos Joel

Reputation: 2389

Remember that String is Immutable, any modification should be assigned to a new String.

   String trimmed = name.replace(" ","");
   System.out.println(trimmed);

Upvotes: 2

jhamon
jhamon

Reputation: 3691

Notice how replacereturns a a string derived from this string (quote from the javadoc). That's because it doesn't change the value of the initial string. In Java String are immutable.

You have to either directly print the result of replace or assign it to a variable.

for(String name : b){
    name = name.replace(" ","");
    System.out.println(name);
}

or shorter:

for(String name : b){
    System.out.println(name.replace(" ",""));
}

Use print instead of printlnif you want to display the whole result on a single line.

Upvotes: 2

Bernardo Moreira
Bernardo Moreira

Reputation: 1

Try to use System.out.print() instead of System.out.println().

System.out.println() will place the cursor in the next line.

Upvotes: -1

Related Questions