Android 拆分字符串 [英] Android Split string
问题描述
我有一个名为 CurrentString
的字符串,它的形式是这样的水果:味道不错"
.
我想使用 :
作为分隔符来拆分 CurrentString
.
这样,"Fruit"
这个词就会被拆分成它自己的字符串,而 "they taste good"
将是另一个字符串.
然后我只想使用 2 个不同的 TextViews
的 SetText()
来显示该字符串.
I have a string called CurrentString
and is in the form of something like this
"Fruit: they taste good"
.
I would like to split up the CurrentString
using the :
as the delimiter.
So that way the word "Fruit"
will be split into its own string and "they taste good"
will be another string.
And then i would simply like to use SetText()
of 2 different TextViews
to display that string.
解决这个问题的最佳方法是什么?
What would be the best way to approach this?
推荐答案
String currentString = "Fruit: they taste good";
String[] separated = currentString.split(":");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"
您可能想要删除第二个字符串的空格:
You may want to remove the space to the second String:
separated[1] = separated[1].trim();
如果你想用像点(.)这样的特殊字符来分割字符串,你应该在点之前使用转义字符
If you want to split the string with a special character like dot(.) you should use escape character before the 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
):
There are other ways to do it. For instance, you can use the StringTokenizer
class (from 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
这篇关于Android 拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!