Android Split字符串

我有一个名为CurrentString的字符串,它的形式是这样的 "Fruit: they taste good"
我想使用:作为分隔符来分割CurrentString。这样的话,单词"Fruit"将被分割成它自己的字符串,而"they taste good"将是另一个字符串。然后我只想使用2个不同的TextViewsSetText()来显示该字符串。< / p >

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

492956 次浏览
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

.split方法将工作,但它使用正则表达式。在这个例子中是(to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

此外,这来自: Android分裂不能正常工作 < / p >

Android用逗号分隔字符串

String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
System.out.println("item = " + item);
}

你也可以考虑Android特有的TextUtils.split ()方法。

TextUtils.split()和String.split()之间的区别是由TextUtils.split()记录的:

string .split()当被拆分的字符串为空时返回["]。返回[]。这不会从结果中删除任何空字符串。

我觉得这是一种更自然的行为。本质上,TextUtils.split()只是String.split()的一个精简包装,专门处理空字符串的情况。方法的代码实际上非常简单。

     String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
StringTokenizer st = new StringTokenizer(s, "|");
String community = st.nextToken();
String helpDesk = st.nextToken();
String localEmbassy = st.nextToken();
String referenceDesk = st.nextToken();
String siteNews = st.nextToken();

字符串s ="字符串="

String[] str = s.split("=");//现在str[0]是“hello”和str[1]是“goodmorning,2,1”

添加这个字符串