Search code examples
javastringtokenizer

I need to extract the first two tokens of a String regardless of how many spaces are in between them


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 " ".


Solution

  • 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];