-1

This code seems like it should remove the spaces, it removes everything but the lowercase letters like I want, but for some reason the spaces stay. What am I doing wrong?

for(int i = 0; i < message.length(); i++){      
    if((int) message.charAt(i) > 122 || (int) message.charAt(i) < 97)
        message = message.replace(message.charAt(i), Character.MIN_VALUE);      
}   
String msg = message.replaceAll("\s", "");
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Ian
  • 17
  • 1
  • Change the '\\s' to '\\s+' \\s is whitespace \\s+ or \\s++ is any amount of whitespace –  Nov 26 '17 at 18:07
  • I am printing out msg right after, and it prints out the string exactly as I want, except the spaces aren't removed. – Ian Nov 26 '17 at 18:08
  • 1
    `String msg = message.replaceAll("\\s", "");` Should work fine. You do not need that for loop to just remove spaces (Don't know what you were trying to do with that one). – nicovank Nov 26 '17 at 18:08
  • The for loop is to remove all characters besides lowercase letters, and it works for everything but spaces. For some reason, the spaces stay in the string, that is my problem. – Ian Nov 26 '17 at 18:10
  • In the for-loop you replace the spaces by zero. If you print the message, these zeros will be displayed as empty spaces. – mayamar Nov 26 '17 at 18:19
  • You're changing `message` in the loop, but assigning the no-whitespace string to `msg`; are you reading `msg` or `message` when you say it doesn't remove whitespace? – Andy Turner Nov 26 '17 at 18:49
  • `message = message.replaceAll("[^a-z]", "");` would work correctly, and wouldn't leave any whitespace to have to remove subsequently. – Andy Turner Nov 26 '17 at 18:50

1 Answers1

-1

Try this :) This create a new string containing no whitespace. And if you need to do it more than once make this to a simple method that returns a string.

String resultStr = "";    
for(int i = 0; i < message.length(); i++){      
       if (!Character.isWhitespace(message.charAt(i)))
       resultStr += message.charAt(i);
    }   

// without whitespace
System.out.print(resultStr);
Stephan D.
  • 254
  • 2
  • 12