Ниже приведены две различные реализации: (1) Использование Map
(2) Использование List
и массива:
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws IOException {
// Test
String[] sentences = { "yes, I have two, three, four numbers.", "I have five, six, seven alphabets.",
"eight, two, five are my lucky numbers.", "Someone gave him FIVE canines and asked him to feed two." };
System.out.println("Using Map: ");
for (String sentence : sentences) {
System.out.println(replaceWordsWithValue1(sentence));
}
System.out.println("Using List and array: ");
for (String sentence : sentences) {
System.out.println(replaceWordsWithValue2(sentence));
}
}
static String replaceWordsWithValue1(String str) {
Map<String, String> wordToDigit = Map.of("two", "2", "three", "3", "four", "4", "five", "5", "six", "6",
"seven", "7", "eight", "8", "nine", "9");
for (String key : wordToDigit.keySet()) {
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(key) + "\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = str.replaceAll(matcher.group(), wordToDigit.get(key));
}
}
return str;
}
static String replaceWordsWithValue2(String str) {
String[] values = { "2", "3", "4", "5", "6", "7", "8", "9" };
List<String> keys = List.of("two", "three", "four", "five", "six", "seven", "eight", "nine");
for (String key : keys) {
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(key) + "\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = str.replaceAll(matcher.group(), values[keys.indexOf(key)]);
}
}
return str;
}
}
Вывод:
Using Map:
yes, I have 2, 3, 4 numbers.
I have 5, 6, 7 alphabets.
8, 2, 5 are my lucky numbers.
Someone gave him 5 canines and asked him to feed 2.
Using List and array:
yes, I have 2, 3, 4 numbers.
I have 5, 6, 7 alphabets.
8, 2, 5 are my lucky numbers.
Someone gave him 5 canines and asked him to feed 2.
Лог c в обеих реализациях прост. Тем не менее, не стесняйтесь комментировать в случае каких-либо сомнений / проблем.