Android拆分字符串

zaid:

我有一个叫做的字符串CurrentString,它的形式像这样"Fruit: they taste good"
我想CurrentString使用:分隔符。
这样一来,单词"Fruit"将被拆分成自己的字符串,"they taste good"并将成为另一个字符串。
然后我只想使用SetText()2种不同的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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章