JBoy
JBoy

Reputation: 5755

Split String into an array of String

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?

Upvotes: 22

Views: 133571

Answers (2)

kuriouscoder
kuriouscoder

Reputation: 5582

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

Upvotes: 7

Staffan Nöteberg
Staffan Nöteberg

Reputation: 4145

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) {
    // 
}

Upvotes: 54

Related Questions