我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
当前回答
将解决方案整合在一起!
public String getFirstNameFromFullName(String fullName){
int indexString = fullName.trim().lastIndexOf(' ');
return (indexString != -1) ? fullName.trim().split("\\s+")[0].toUpperCase() : fullName.toUpperCase();
}
其他回答
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
下面是一个非常简单的例子:
希望能有所帮助。
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
你所拥有的应该有用。但是,如果所提供的空格默认为…别的吗?你可以使用空白正则表达式:
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
这将导致任意数量的连续空格将字符串分割为令牌。
如果你不想使用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;
}
试试这个
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);