我需要用空格分割我的字符串。 为此我试过:

str = "Hello I'm your String";
String[] splited = str.split(" ");

但这似乎并不奏效。


当前回答

试试这个

    String str = "This is String";
    String[] splited = str.split("\\s+");

    String split_one=splited[0];
    String split_second=splited[1];
    String split_three=splited[2];

   Log.d("Splited String ", "Splited String" + split_one+split_second+split_three);

其他回答

你可以使用下面的代码分离字符串:

   String theString="Hello world";

   String[] parts = theString.split(" ");

   String first = parts[0];//"hello"

   String second = parts[1];//"World"

使用Stringutils.split()按白色步长分割字符串。例如StringUtils。split("Hello World")返回"Hello"和"World";

为了解决上述情况,我们采用了这样的分割方法

String split[]= StringUtils.split("Hello I'm your String");

当我们打印拆分数组时,输出将是:

你好

I'm

your

字符串

完整的示例演示检查这里

另一种方法是:

import java.util.regex.Pattern;

...

private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split

在这里看到的

因为这些答案已经发布了一段时间了,下面是另一种更流行的回答方法:

List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
    while (sc.hasNext()) output.add(sc.next());
}

现在你有了一个字符串列表(可以说比数组更好);如果你确实需要一个数组,你可以做输出。toArray(新的字符串[0]);

好的,我们要做拆分因为你已经得到答案了,我要推广一下。

如果要用空格分隔任何字符串,请使用分隔符(特殊字符)。

首先,删除前导空格,因为它们造成了大多数问题。

str1 = "    Hello I'm your       String    ";
str2 = "    Are you serious about this question_  boy, aren't you?   ";

首先去掉前导空格,可以是空格、制表符等。

String s = str1.replaceAll("^\\s+","");//starting with whitespace one or more

如果你想按空格或任何特殊字符分割。

String[] sa = s.split("[^\\w]+");//split by any non word char

但是由于w包含[a-zA-Z_0-9],所以如果你想用下划线(_)分割也可以使用

 String[] sa = s.split("[!,? ._'@]+");//for str2 after removing leading space