Reputation: 75
In a program where currency is input in the form £2 or 10p, for example, is there a method to split this into two variables in the form currencyType = £ currencyValue = 2 or currencyType = p currencyValue = 10
where currencyType is a string and currencyValue is an int?
Upvotes: 0
Views: 799
Reputation: 174706
Use patten and matcher classes like below. \d+
matches one or more digits where \D+
matches one or more non-digit characters.
String s1 = "£2";
Matcher m = Pattern.compile("(\\D+)|(\\d+)").matcher(s1);
while(m.find())
{
if (m.group(1) != null)
System.out.println("Currency Type: " + m.group(1));
if (m.group(2) != null)
System.out.println("Currency Value: " + m.group(2));
}
Output:
Currency Type: £
Currency Value: 2
OR
Use this regex, if you want to deal also with the decimal value.
Pattern.compile("(\\D+)|(\\d+(?:\\.\\d+)?)");
Upvotes: 1
Reputation: 4239
An idea for a solution without regular expressions, although I'd prefer one of those:
String entry = "€2.73";
StringBuilder currency = new StringBuilder();
StringBuilder value = new StringBuilder();
for (char c : entry.toCharArray()) {
if (Character.isDigit(c) || c == '.' || c == ',') {
value.append(c);
} else {
currency.append(c);
}
}
System.out.println("Value = " + value + " Currency = " + currency);
Upvotes: 1
Reputation: 124
You can input your value as a string, split it normally with the split function and assign each value to its own string. Then convert the string to an integer.
int currencyValue = Integer.parseInt(array[0]); String currencyType = array[1];
array[] is the array that you split the string into.
String input = user_input.nextLine();
char[] array = input.toCharArray();
for(int i = 0; i < input.length(); i++) {
if (Character.isLetter(array[i])){
//use .split based on the output of the if statement
}
}
Upvotes: -1
Reputation: 1406
You can use this regular expression to get your result: "(.*?)([\\d,]*)(.*?)"
This will split the input into three groups:
1) Leading currency token
2) Value token (can contain a ',', in the string version you can replaceAll ',' with '' and then convert to integer)
3) Trailing currency token
By looking at the groups from the regex, you can figure out if the leading or trailing currency is present and then get the value from the second group. You can write the code yourself by looking up usage for java regex.
Upvotes: 0