1

I have a problem in finding the right way to only get city1, city 2 and the distance without the "km", using a scanner and delimiter. I need to get the text in bold.
String (example):

city1, country; city2, country; 145 km

My Delimitar so far because I really have no idea:

scanner.useDelimiter(";");

I also tried using string.split("") without success.

Should I first devide it in 3 parts on the ";" and do a new delimitar for each part? Or is there an easier way?

Thanks in advance

(Edit to explain difference to another post: I tried it with regex, with also no luck. I need to split the string on multiple places on different characters. I wouldn't ask a question if I'm able to solve it with another post.)

Matti VM
  • 649
  • 1
  • 5
  • 17

2 Answers2

0

You can try with String.split()

String data = "city1, country; city2, country; 145 km";
String city1Val = data.split(";")[0].split(",")[0];
String city1Con = data.split(";")[0].split(",")[1];
String city2Val = data.split(";")[1].split(",")[0];
String city2Con = data.split(";")[1].split(",")[1];
String distance = data.split(";")[2];

Note: If you want distance as number, try as follows,

distance = distance.replaceAll("[^\\d.]", "");
Rakesh KR
  • 6,049
  • 5
  • 39
  • 49
  • Thank you for your answer. The other answer just fitted better for me. For the distance I already used a substring: distance.substring(0, distance.length()-3). – Matti VM Aug 14 '17 at 19:51
0

You can use a combination of Scanner and String#split:

String source = "city1, country; city2, country; 145 km";
Scanner scanner = new Scanner(source);
scanner.useDelimiter(";");

while (scanner.hasNext()) {
    // trim() removes leading and trailing whitespace
    String line = scanner.next().trim();
    // split the line on either ',' or a space
    String[] split = line.split(",|\\s");
    // print the first word
    System.out.println(split[0]);
}
Luciano van der Veekens
  • 5,586
  • 4
  • 21
  • 29