我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
当前回答
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
其他回答
将解决方案整合在一起!
public String getFirstNameFromFullName(String fullName){
int indexString = fullName.trim().lastIndexOf(' ');
return (indexString != -1) ? fullName.trim().split("\\s+")[0].toUpperCase() : fullName.toUpperCase();
}
因为这些答案已经发布了一段时间了,下面是另一种更流行的回答方法:
List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
while (sc.hasNext()) output.add(sc.next());
}
现在你有了一个字符串列表(可以说比数组更好);如果你确实需要一个数组,你可以做输出。toArray(新的字符串[0]);
不仅是空白,我的解决方案也解决了看不见的字符。
str = "Hello I'm your String";
String[] splited = str.split("\p{Z}");
你可以使用下面的代码分离字符串:
String theString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
简单的吐串由空间
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());
}
}