首页 > 解决方案 > 如何使用分隔符按字符串(逐字而不是字符)从字符串数组 [] 中拆分字符串?

问题描述

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 以使字符串被 || 分割。管道符号,但我得到的字符如何像以前一样

标签: javastring

解决方案


不要使用两次拆分方法。您可以使用一种拆分方法完成任务。像这样,

 void displayResult() {

   String str = "tamilnadu||chennai-karanataka||bengaluru";

   String[] res = str.split("\\|\\||-");

   for(String city : res){

     System.out.println(city);

   }

 }

你的输出将是: -

泰米尔纳德邦

钦奈

卡拉纳塔克

班加罗尔


推荐阅读