Split String into an array of String
130,715
Solution 1
You need a regular expression like "\\s+"
, which means: split whenever at least one whitespace is encountered. The full Java code is:
try {
String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
//
}
Solution 2
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods
Related videos on Youtube
Comments
-
JBoy almost 2 years
I'm trying to find a way to split a String into an array of String(s), and I need to split it whenever a white spice is encountered, example
"hi i'm paul"
into"
"hi" "i'm" "paul"
How do you represent white spaces in split() method using RegularExpression?
-
Mohamed Nuur almost 13 yearswhy do you even need regular expression for that? couldn't you just do
String[] myList = myString.split(" ");
-
Johan almost 13 yearsThere is a tool called Visual REGEXP (laurent.riesterer.free.fr/regexp) it can help you visualise the result of you regexp (perl regexp that is, but more or less all lang is using perl regexp so that is not a problem)
-
Stephen C almost 13 years"i dont know that much yet about RegExp" - sounds like you need to remedy that, because asking someone else to write your regexes for you is not sustainable.
-
-
Staffan Nöteberg almost 13 years@Gabe: I don't think so. He wants anything, except whitespeces. For example he wants the apostrophe in "i'm" to be kept together with the i and the m.
-
Gabe almost 13 yearsOops, I meant
\s+
! (as you have it now)