Dominik
Dominik

Reputation: 4768

Java String Manipulation: extracting integer and float from string based on pattern

I have the following two possible contents of a String. Obviously the amounts always vary and I would like to extract the key information and

Case 0:   pricesString = ""
Case 1:   pricesString = "$0.023"
Case 2:   pricesString = "10+: $1.46 100+: $0.16 500+: $0.04"

In Case 0 I would like to do nothing.

In Case 1 I would like to perform:

article.addPrice(1, 0.023);

In Case 2 I would like to perform:

article.addPrice(10, 1.46);
article.addPrice(100, 0.16);
article.addPrice(500, 0.04);

How can I extract this information so I can can call article.addPrice with the float and integer values contained?

Upvotes: 2

Views: 2069

Answers (2)

marc
marc

Reputation: 6223

Apply the regex \d+\.?\d* as often as you can. The array of the results can be checked whether it contains 0, 1 or more values.

If there are 0, it is Case 0.

If there is one, it is Case 1. You can edd it with qunantity 1 to the articles.

If there are more, you can loop with something like

for(int i = 0; i < result.length / 2; i++) {
    articles.addArticle(Integer.parseInt(result[i]), Double.parseDouble(result[i+1]));
}

Upvotes: 0

Bozho
Bozho

Reputation: 597224

That looks like a job for regex:

String pricesString = "10+: $1.46 100+: $0.16 500+: $0.04";
Pattern p = Pattern.compile("(\\d+)\\+: \\$(\\d\\.\\d\\d)");
Matcher m = p.matcher(pricesString);
while (m.find()) {
    Intger.parseInt(m.group(1));
    Double.parseDouble(m.group(2));
}

You can choose between the 3 cases by a simple .length() check. The code above is for the last case. The rest is eaiser

Upvotes: 5

Related Questions