我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
当前回答
另一种方法是:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
在这里看到的
其他回答
另一种方法是:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
在这里看到的
你所拥有的应该有用。但是,如果所提供的空格默认为…别的吗?你可以使用空白正则表达式:
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
这将导致任意数量的连续空格将字符串分割为令牌。
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
简单的吐串由空间
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());
}
}
我相信在str.split括号中放入正则表达式应该可以解决这个问题。Java String.split()方法是基于正则表达式的,所以你需要:
str = "Hello I'm your String";
String[] splitStr = str.split("\\s+");