John
John

Reputation: 281

extract float values from a string

I have a long string like "abc_12.23;dcf_23.99;dfa_12.99; and so on.

Now i need to create a to seperate the float and the string values into a float and a string array respectively.

I tried with splitting them on ";" and took it in an array and then performed a split over "_" and extracted them in an array. But it was not working. Can anyone help me on this??

Upvotes: 2

Views: 1933

Answers (5)

Paweł Adamski
Paweł Adamski

Reputation: 3415

You might use Scanner. It would look like this:

scanner = Scanner("abc_12.23;dcf_23.99;dfa_12.99;");
scanner.useDelimiter("[;_]");
while(scanner.hasNext()){
  String s = scanner.next();
  float f = scanner.nextFloat();
}

Upvotes: 0

DwB
DwB

Reputation: 38320

Try this regular expression:

(\w.)_(\d.\.\d.);

Test it here A Regular Expression Test Applet

Use matcher.find() to step through the matches.

Group 3 (index 2) will have the float value.

Upvotes: 0

jlordo
jlordo

Reputation: 37823

Here's a regex solution:

    String input = "abc_12.23;dcf_23.99;dfa_12.99; and so on";
    String regex = "([a-zA-Z]+)_(\\d+(\\.\\d+)?);?";
    List<String> strings = new ArrayList<>();
    List<Double> floats = new ArrayList<>();
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        strings.add(matcher.group(1));
        floats.add(Double.valueOf(matcher.group(2)));
    }
    System.out.println(strings); // prints [abc, dcf, dfa]
    System.out.println(floats); // prints [12.23, 23.99, 12.99]

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Arguably, using StringTokenizer might be more a little more efficient

    StringTokenizer st = new StringTokenizer("abc_12.23;dcf_23.99;dfa_12.99", "_;");
    int n = st.countTokens();
    String[] sa = new String[n / 2];
    float[] fa = new float[n / 2];
    for(int i = 0 ; st.hasMoreTokens(); i++) {
        sa[i] = st.nextToken();
        fa[i] = Float.parseFloat(st.nextToken());
    }

Upvotes: 2

Анатолий
Анатолий

Reputation: 2857

You solution is good.

Followig approach a bit increase performance:

  • Iterate all chars into string.
  • When you found "_" or ";" copy substring from last same char (if current ; parsed is float, it _ than parsed is string) and push into appropriate array.

Not sure that your improve performance greatelly.

Note: I not java pro, but if java allow spilt by several chars just split by ";" and"_" and use odd indexes for floats and not odd for strings.

Upvotes: 0

Related Questions