java - Android 拆分字符串

标签 java android string

我有一个名为 CurrentString 的字符串,其形式如下 “水果:它们味道不错”
我想使用 : 作为分隔符来拆分 CurrentString
这样,"Fruit" 这个词将被拆分成它自己的字符串,而 "它们味道不错" 将是另一个字符串。
然后我会只是喜欢使用 2 个不同的 TextViewsSetText() 来显示该字符串。

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

最佳答案

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/

相关文章:

C# ASP.net,使用字符串变量存储和编写 HTML

python - 组合字符串列表,提高性能

java - 使用java处理外部窗口

java - 确定企业 Web 应用程序的服务器硬件要求

java - 使用泛型返回接口(interface)时使用什么数据类型?

java - 'finally'如何阻止android运行

java - Android:在没有额外支持库的情况下滑动 View

java同步

android - 漏洞 : Splash and Icon generator not working (Ionic and Cordova)

javascript - 在 Javascript 中可以选择字符串中的单词吗?