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.

heisenberg
  • 1,784
  • 4
  • 33
  • 62

2 Answers2

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 . 
Naveen Kumar
  • 893
  • 11
  • 19
  • 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. – heisenberg May 03 '18 at 05:40
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+" ");
}
cloudiebro
  • 135
  • 3
  • 13