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

Share:
130,715

Related videos on Youtube

JBoy
Author by

JBoy

Beginner java/jsp developer

Updated on July 09, 2022

Comments

  • JBoy
    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
      Mohamed Nuur almost 13 years
      why do you even need regular expression for that? couldn't you just do String[] myList = myString.split(" ");
    • Johan
      Johan almost 13 years
      There 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
      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
    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
    Gabe almost 13 years
    Oops, I meant \s+! (as you have it now)