正则表达式.将字符串数组拆分两次



我有一个带有州城市值的文本文件:-这些是我文件中的内容:-

Madhya Pradesh-Bhopal
Goa-Bicholim
Andhra Pradesh-Guntur

我想分裂州和城市...这是我的代码

   FileInputStream fis= new FileInputStream("StateCityDetails.txt");
    BufferedInputStream bis = new BufferedInputStream(fis);
    int h=0;
    String s;
    String[] str=null;
    byte[] b= new byte[1024];
    while((h=bis.read(b))!=-1){
     s= new String(b,0,h);
    str= s.split("-");
    }
    for(int i=0; i<str.length;i++){
        System.out.println(str[1]);  ------> the value at 1 is Bhopal Goa
    }
       }

我在中央邦之间也有一个空间。所以我想删除文件中各州之间的空格,并拆分州和城市并获得以下结果:-

     str[0]----> MadhyaPradesh
     str[1]----> Bhopal
     str[2]-----> Goa
     str[3]----->Bicholim

请帮忙..提前谢谢你:)

我会在这里使用BufferedReader,而不是你这样做的方式。 下面的代码片段读取每一行,在连字符 ( - 上拆分,并删除每个部分的所有空格。 每个组件都按从左到右(从上到下)的顺序输入到列表中。 该列表在末尾转换为数组,以备不时之需。

List<String> names = new ArrayList<String>();
BufferedReader br = null;
try {
    String currLine;
    br = new BufferedReader(new FileReader("StateCityDetails.txt"));
    while ((currLine = br.readLine()) != null) {
        String[] parts = currLine.split("-");
        for (int i=0; i < parts.length; ++i) {
            names.add(parts[i].replaceAll(" ", ""));
        }
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
    if (br != null) br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
// convert the List to an array of String (if you require it)
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
// print out result
for (String val : nameArr) {
    System.out.println(val);
}

最新更新