Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

Java - String splitting

I read a txt with data in the following format: Name Address Hobbies

Example(Bob Smith ABC Street Swimming)

and Assigned it into String z

Then I used z.split to separate each field using " " as the delimiter(space) but it separated Bob Smith into two different strings while it should be as one field, same with the address. Is there a method I can use to get it in the particular format I want?

P.S Apologies if I explained it vaguely, English isn't my first language.

String z;
try {
    BufferedReader br = new BufferedReader(new FileReader("desc.txt"));
    z = br.readLine();
} catch(IOException io) { 
    io.printStackTrace();
}
String[] temp = z.split(" ");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the format of name and address parts is fixed to consist of two parts, you could just join them:

String z = "";  // z must be initialized

// use try-with-resources to ensure the reader is closed properly
try (BufferedReader br = new BufferedReader(new FileReader("desc.txt"))) {
    z = br.readLine();
} catch(IOException io) { 
    io.printStackTrace();
}

String[] temp = z.split(" ");

String name = String.join(" ", temp[0], temp[1]);
String address = String.join(" ", temp[2], temp[3]);
String hobby = temp[4];

Another option could be to create a format string as a regular expression and use it to parse the input line using named groups (?<group_name>capturing text):

// use named groups to define parts of the line
Pattern format = Pattern.compile("(?<name>\w+\s\w+)\s(?<address>\w+\s\w+)\s(?<hobby>\w+)");
Matcher match = format.matcher(z);
if (match.matches()) {
    String name = match.group("name");
    String address = match.group("address");
    String hobby = match.group("hobby");
    System.out.printf("Input line matched: name=%s address=%s hobby=%s%n", name, address, hobby);
} else {
    System.out.println("Input line not matching: " + z);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...