我有一个名为CurrentString的字符串,其形式如下

最好的方法是什么?

推荐答案

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相关问答推荐

如何将一些命令写入Chrome控制台,然后使用Java将输出存储在selenium中

摆脱双列举导致的Json解析错误问题

如果它最终将被转换为int类型,为什么我们在Java中需要较小的integer类型?

使用hibiter中特定字段的where条款自定义映射

将@ManyToOne JPA Composite Key用作Id保存实体添加额外参数

gitlab ci不会运行我的脚本,因为它需要数据库连接'

由于我在Main方法中关闭了 scanner ,但在该方法中创建了一个新的 scanner ,因此出现了错误

Mapstruct不能正确/完全映射属性

Java-动态绑定-问题-了解

如何在Java记录中设置BigDecimal类型属性的精度?

如何让JVM在SIGSEGV崩溃后快速退出?

使用Jolt将字段转换为列表

使SLF4J在Android中登录到Logcat,在测试中登录到控制台(Gradle依赖问题)

为什么当我创建Robot对象时,JavaFX引发IlLegalStateException异常?

Java泛型类方法的静态返回类型是否被类型擦除?

来自外部模块的方面(对于Java+Gradle项目)不起作用

如何配置空手道以使用FeignClient或RestTemplate代替ApacheHttpClient

如何在运行docker的应用程序中获取指定的配置文件

根据应用程序 Select 的语言检索数据

原始和参数化之间的差异调用orElseGet时可选(供应商)