This code snippet show you how to split string with multiple white-space characters. To split the string this way we use the "\s+"
regular expression. The white-space characters include space, tab, line-feed, carriage-return, new line, form-feed.
Let’s see the code snippet below:
package org.kodejava.lang;
import java.util.Arrays;
public class SplitStringMultiSpaces {
public static void main(String[] args) {
String text = "04/11/2021 SHOES RUNNING RED 99.9 USD";
// Split the string using the \s+ regex to split multi spaces
// line of text.
String[] items = text.split("\\s+");
System.out.println("Length = " + items.length);
System.out.println("Items = " + Arrays.toString(items));
}
}
The result of the code snippet is:
Length = 6
Items = [04/11/2021, SHOES, RUNNING, RED, 99.9, USD]
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023
Thanks for sharing this. Indeed helpful
But this is not working for me.
Is there any alternate solution?
Hi Sudheen,
Just try the code snippet in the post to prove that it works. Why did you check if the string contains
\\s+
text? Because it will simple check if your text contains that string. And also when you are using thevar
keyword you don’t need to define the variable type anymore.