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

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

但这似乎并不奏效。


当前回答

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

   String theString="Hello world";

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

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

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

其他回答

不仅是空白,我的解决方案也解决了看不见的字符。

str = "Hello I'm your String";
String[] splited = str.split("\p{Z}");

简单的吐串由空间

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

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

   String theString="Hello world";

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

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

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

试试这个

    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 split方法,那么你可以使用Java中的StringTokenizer类作为..

    StringTokenizer tokens = new StringTokenizer("Hello I'm your String", " ");
    String[] splited = new String[tokens.countTokens()];
    int index = 0;
    while(tokens.hasMoreTokens()){
        splited[index] = tokens.nextToken();
        ++index;
    }