lukhrs
lukhrs

Reputation: 13

Split a string you’ve entered with scanner

I have a problem. I want to type in a string (with Java.util.scanner) with two words. Then I want the program to split my entered string at the whitespace, save both substrings in a seperate variable and make a output in the end.

I know that you can split strings with

String s = "Hello World";
String[] = s.split(" ");

But it doesnt seem to work when your String is

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();

Any help? Thank you very much

Upvotes: 1

Views: 2384

Answers (3)

Nehorai Elbaz
Nehorai Elbaz

Reputation: 2452

Your code works for me:

String s;
s=sc.nextLine();

String[] words=s.split(" "); 
for(String w:words){  
System.out.print(w+" ");  
}

input: "Hello world"

output: "Hello world"

Upvotes: 1

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

You may also want to try this way of splitting String that you get from user input:

Scanner sc = new Scanner(System.in);
String[] strings = sc.nextLine().split("\\s+");

If you simply want to print array containing these separated strings, you can do it without using any loop, simply by using:

Arrays.toString(strings);

If you want to have your printed strings to look other way, you can use for it simple loop printing each element or by using StringBuilder class and its append() method - this way may be faster than looping over longer arrays of strings.

Upvotes: 0

kkica
kkica

Reputation: 4104

s.split("\\s+"); will split your string, even if you have multiple whitespace characters (also tab, newline..)

You can also use from java.util package

    StringTokenizer tokens = new StringTokenizer(s.trim());
    String word;
    while (tokens.hasMoreTokens()) {
        word = tokens.nextToken();

    }

Or from Apache Commons Lang

StringUtils.split(s)

Upvotes: 2

Related Questions