Bhavana_1622 Bhavana_1622 - 8 months ago 43
Java Question

Regular Expression..Splitting a string array twice

I have a text file with state-city values:-
These are the contents in my file:-

Madhya Pradesh-Bhopal
Andhra Pradesh-Guntur

I want to split the state and the city... Here is my code

FileInputStream fis= new FileInputStream("StateCityDetails.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int h=0;
String s;
String[] str=null;
byte[] b= new byte[1024];
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

Also I have a space between Madhya Pradesh..
So i want to Remove spaces between the states in the file and also split the state and city and obtain this result:-

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

Please Help..Thank you in advance :)


I would use a BufferedReader here, rather than the way you are doing it. The code snippet below reads each line, split on hyphen (-), and removes all whitespace from each part. Each component is entered into a list, in left to right (and top to bottom) order. The list is converted to an array at the end in case you need this.

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) {
} finally {
    try {
    if (br != null) br.close();
    } catch (IOException ex) {

// 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) {