-1

I have list of food prices displayed in an EditText, so how can I iterate over them and extract all prices? For example here I want to extract prices between : and L .

I was trying to use StringTokenizer but don't know how to use it...

enter image description here

AlexTa
  • 5,133
  • 3
  • 29
  • 46
André Abboud
  • 1,864
  • 2
  • 14
  • 23

3 Answers3

3

Try this

StringTokenizer tokenizer = new StringTokenizer(string, ":L");
while (tokenizer.hasMoreTokens()) {
    try {
        int price = Integer.parseInt(tokenizer.nextToken());
    } catch (NumberFormatException e) {
        continue;
    }
}
tompee
  • 1,408
  • 1
  • 7
  • 6
2

Try the following using regex:

final String s = "Price:1500L.L";
final Pattern p = Pattern.compile(":.*?L");
final Matcher m = p.matcher(s);
if (m.find()) {
    final String result = m.group().subSequence(1, m.group().length() - 1).toString();
    //result = 1500
}
AlexTa
  • 5,133
  • 3
  • 29
  • 46
1

I test some code in Java. This may help

private static int getSum(String test) {
    String[] res1 = test.replace("Price:", "-").replace("L.L", "-").split("-");
    int sum = 0;
    for (String s : res1) {
        try {
            sum += Integer.valueOf(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return sum;
}
Rust Fisher
  • 331
  • 3
  • 12