Reputation: 25
I need to extract only the first two tokens of a String regardless of how many spaces are between them. I then need to store those two extracted tokens in two separate Strings.
The code that I have works if there is only one space between the Strings. If there is more than one space then it considers the second space as the second String.
String splitTokens = "Hello World this is a test";
String extractTokens[] = splitTokens.split(" ", 3);
String firstString = extractTokens[0];
String secondString = extractTokens[1];
Expected result: firstString is "Hello" and secondString is "World".
Actual result: firstString is "Hello" and secondString is " ".
Upvotes: 1
Views: 407
Reputation: 521194
You should split on \s+
, that is, one or more spaces/whitespace characters:
String splitTokens = "Hello World this is a test";
String[] extractTokens = splitTokens.split("\\s+", 3);
String firstString = extractTokens[0];
String secondString = extractTokens[1];
Upvotes: 3