-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", "");
7
  • Change the '\\s' to '\\s+' \\s is whitespace \\s+ or \\s++ is any amount of whitespace Commented Nov 26, 2017 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. Commented Nov 26, 2017 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). Commented Nov 26, 2017 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. Commented Nov 26, 2017 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. Commented Nov 26, 2017 at 18:19

1 Answer 1

-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);
Sign up to request clarification or add additional context in comments.

7 Comments

You could do it more effecient with ascii codes instead :)
Any reason to use String instead of StringBuilder here?
Let's avoid "try this" code dump answers. At least explain what you're doing what the problem is. Make the answer useful to more than just the OP. Please comment back once fixed.
Note that this doesn't remove whitespace, it just removes some whitespace. Use Character.isWhitespace(message.charAt(i)) as the condition to handle all whitespace.
@Marc.9 you don't need to cast a char to an int (it is widened automatically); and using ' ' is preferable to using a magic number.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.