我有一个包含州/城市值的文本文件:- 这些是我的文件中的内容:-
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);
}
关于java - 正则表达式..将字符串数组分割两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259352/