安卓拆分字符串
我有一个名为的字符串,其形式如下。
我想拆分使用作为分隔符。
这样,单词将被拆分成自己的字符串,并且将是另一个字符串。
然后我只想使用2个不同的来显示该字符串。CurrentString
"Fruit: they taste good"
CurrentString
:
"Fruit"
"they taste good"
SetText()
TextViews
解决这个问题的最佳方法是什么?
我有一个名为的字符串,其形式如下。
我想拆分使用作为分隔符。
这样,单词将被拆分成自己的字符串,并且将是另一个字符串。
然后我只想使用2个不同的来显示该字符串。CurrentString
"Fruit: they taste good"
CurrentString
:
"Fruit"
"they taste good"
SetText()
TextViews
解决这个问题的最佳方法是什么?
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
您可能希望删除第二个字符串的空格:
separated[1] = separated[1].trim();
如果要使用像 dot(.) 这样的特殊字符拆分字符串,则应在点前使用转义字符 \
例:
String currentString = "Fruit: they taste good.very nice actually";
String[] separated = currentString.split("\\.");
separated[0]; // this will contain "Fruit: they taste good"
separated[1]; // this will contain "very nice actually"
还有其他方法可以做到这一点。例如,您可以使用类(从):StringTokenizer
java.util
StringTokenizer tokens = new StringTokenizer(currentString, ":");
String first = tokens.nextToken();// this will contain "Fruit"
String second = tokens.nextToken();// this will contain " they taste good"
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
.split 方法将起作用,但它使用正则表达式。在这个例子中,它将是(从克里斯蒂安那里偷窃):
String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
另外,这来自:Android拆分无法正常工作