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

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

但这似乎并不奏效。


当前回答

简单的吐串由空间

    String CurrentString = "First Second Last";
    String[] separated = CurrentString.split(" ");

    for (int i = 0; i < separated.length; i++) {

         if (i == 0) {
             Log.d("FName ** ", "" + separated[0].trim() + "\n ");
         } else if (i == 1) {
             Log.d("MName ** ", "" + separated[1].trim() + "\n ");
         } else if (i == 2) {
             Log.d("LName ** ", "" + separated[2].trim());
         }
     }

其他回答

Try

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

http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html

试试这个

    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);

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

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

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

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

char用单引号代替双引号

String[] split = str.split(' ');

下面是一个非常简单的例子:

希望能有所帮助。

String str = "Hello I'm your String";
String[] splited = str.split(" ");
var splited = str.split(" ");
var splited1=splited[0]; //Hello
var splited2=splited[1]; //I'm
var splited3=splited[2]; //your
var splited4=splited[3]; //String