我有一个名为 CurrentString
的字符串,其形式如下
“水果:它们味道不错”
。
我想使用 :
作为分隔符来拆分 CurrentString
。
这样,"Fruit"
这个词将被拆分成它自己的字符串,而 "它们味道不错"
将是另一个字符串。
然后我会只是喜欢使用 2 个不同的 TextViews
的 SetText()
来显示该字符串。
解决此问题的最佳方法是什么?
最佳答案
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();
如果你想用点(.)这样的特殊字符分割字符串,你应该在点之前使用转义字符\
例子:
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
关于java - Android 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732790/