-1

I have a string like "your identification code is four zero two four three six". I want to extract "four zero two four three six" from this , and then convert it to '402436'. Note that , the text "your identification code is" will always be there, but the numbers might change.

Need help/guidance to perform this activity in java.

Niladri
  • 29
  • 4
  • I think that String::replace would be better/easier – Scary Wombat Oct 13 '22 at 08:31
  • I am unaware of any language that can convert a number represented in text (as in 'FOUR') to its numerical value (as in 4). You might want to use some sort of mapping where one => 1, two =>2, etc. – DarknessPlusPlus Oct 13 '22 at 08:33
  • String replace fires up the whole regular expression engine, so for me, substring is much faster and simpler. You could run into trouble with replace if there were non-alphabetic characters in the first part of the string. – rghome Oct 13 '22 at 08:36
  • Also, for converting words to numbers, see: https://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java – rghome Oct 13 '22 at 08:37
  • Does this answer your question? [How to convert number to words in java](https://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java) – rghome Oct 13 '22 at 08:38

2 Answers2

1

Use String#substring to extract your digits, String#split to get an array of digits and then loop over them (classic loop or stream API) to look up numeric values for the digit words. You can use a switch-case statement or a lookup map for the last step. Finally, sum and multiply your digits

final Map<String, Integer> digitmap = Map.ofEntries(
    Map.entry("zero", 0),
    Map.entry("one", 1),
    Map.entry("two", 2),
    …);
final String input = "…";
final String[] digitwords = input.substring("your identification code is ".length()).split(" ");
final List<Integer> digits = Arrays.stream(digitwords)
    .map(digitmap::get)
    .toList();
long result = 0;
for (int i = 0; i < digits.size(); ++i) {
  result = result*10 + digits.get(i);
}

If you want a string and preserve leading zeros, then don't map "zero" -> 0, but "zero" -> "0" and then String.join instead of sum + multiply or collect in a string builder:

final Map<String, String> digitmap = Map.ofEntries(
    Map.entry("zero", "0"),
    …);
// …
final StringBuilder sb = new StringBuilder(digitwords.size());
for (final String digit : digitwords) {
  sb.append(digitmap.get(digit));
}
final String result = sb.toString();
knittl
  • 246,190
  • 53
  • 318
  • 364
0

Try this.

String input = "your identification code is four zero two four three six";
Map<String, String> map = Map.of(
    "zero", "0", "one", "1", "two", "2", "three", "3", "four", "4",
    "five", "5", "six", "6", "seven", "7", "eight", "8", "nene", "9"
);
String output = Stream.of(input.split("\\s+"))
    .map(w -> map.getOrDefault(w, ""))
    .collect(Collectors.joining());
System.out.println(output);

output:

402436