java - 如何使用分隔符按字符串(逐字而不是字符)从字符串数组 [] 中拆分字符串?
问题描述
void displayResult() {
String str = "tamilnadu||chennai-karanataka||bengaluru";
String[] res = str.split("\\-");
System.out.println(res.length);//res length is 2
//res contains two strings splited by -
String[] result = res.toString().split("\\||");
//again splitting by || but getting as characters, i need to get word by word
// how to achieve this
System.out.println(result.length);//result length is 28
}
// i was supposed to get tamilnadu and chennai from first string[] res
String[] res 包含两个被分割的字符串 - 我试图以相同的方式分割 res 以使字符串被 || 分割。管道符号,但我得到的字符如何像以前一样
解决方案
不要使用两次拆分方法。您可以使用一种拆分方法完成任务。像这样,
void displayResult() {
String str = "tamilnadu||chennai-karanataka||bengaluru";
String[] res = str.split("\\|\\||-");
for(String city : res){
System.out.println(city);
}
}
你的输出将是: -
泰米尔纳德邦
钦奈
卡拉纳塔克
班加罗尔
推荐阅读
- javascript - Socket IO多次发出代理消息
- algorithm - 图中的所有链
- nginx - Nginx 返回 404
- ios - 使用系统应用程序选择器打开任意文件
- python - 无法更改数据框中的值?
- python - 使用 TensorFlow Serving (Tensorflow 2.2) 为 Keras 模型提供服务的非确定性结果
- r - 在 R 包中使函数完全不可访问
- swift - 如何在 SwiftUI 中将变量从“更高视图”转换为“下视图”?
- express - 无服务器快速应用程序在路由中的逻辑完成之前终止
- c++ - 通过再次用自己替换某些字符重新编译时,完全相同的代码会产生不同的输出?