0

I tried to do some String manipulation to play around with the methods available and I noticed that when I used the replaceAll("\\s+","") method to remove whitespaces in a String, it failed to do it.

System.out.print("Enter a word: ");
String word = scanner.next();
String cleansed = word.replaceAll("\\s+","");
char[] letters = cleansed.toCharArray();
for(char c : letters){
    System.out.print(c+" ");
}

When I go to the console and do something like,

Enter a word : I am entering some word.

The output I get on the console is I which seems to be dropping all other String values after the space.

What am I missing here?

I play around with different methods when there's nothing to do. So right now I just wonder why it's not working as expected.

I'd appreciate any help.

Thank you.

4
  • Please check this stackoverflow.com/a/26931946/540195 Commented May 3, 2018 at 5:23
  • Can't reproduce. Maybe you tested with different content. Although it doesn't work as you expect anyway... Note that NOT all String.replace* methods take a regex... Commented May 3, 2018 at 5:26
  • I see you used replace("\\s+","") but you mentioned replaceAll("\\s+","") Commented May 3, 2018 at 5:27
  • @DeepakSharma I edited the question. I'm using the latter which is replaceAll("\\s+",""); Commented May 3, 2018 at 5:33

2 Answers 2

2

You should use scanner.nextLine() instead of scanner.next(). Also use word.replaceAll() instead of word.replace()

Here is the working code:

import java.util.Scanner;

public class Example {
    public static void main(String[] a) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = scanner.nextLine();
        String cleansed = word.replace("\\s+","");
        char[] letters = cleansed.toCharArray();
        for(char c : letters){
            System.out.print(c+" ");
        }
    }
}

The output will be:

Enter a word: Enter a word : I am entering some word.
E n t e r a w o r d : I a m e n t e r i n g s o m e w o r d . 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I failed to notice that at first. The code actually comes with other code blocks prior to this which is using the scanner methods next(), nextLine(). I suspect that the next() and nextLine() and nextInt() methods are getting mixed up since I'm using one scanner object.
0

try this

System.out.print("Enter a word: ");
String word = scanner.next();
word = word.replaceAll(" ","");
char letters [] = word.toCharArray();
for(char c : letters){
    System.out.print(c+" ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.