一尘不染

Android拆分字符串

android java

我有一个名为的字符串CurrentString,其形式像这样 "Fruit: they taste good"
我想CurrentString使用:分隔符。
这样一来,单词"Fruit"将被拆分成自己的字符串,"they taste good"并将成为另一个字符串。
然后我只想使用SetText()2种不同的TextViews字符串来显示该字符串。

解决这个问题的最佳方法是什么?


阅读 355

收藏
2020-03-21

共1个答案

一尘不染

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
2020-03-21