用另一个多个字符串替换多个字符串

huangapple go评论77阅读模式
英文:

Replace the multiple string with the other multiple string

问题

Sure, here's the translated content:

我有类似以下的字符串 -

  1. 是的,我有两个、三个、四个数字。
  2. 我有五个、六个、七个字母。
  3. 八、二、五是我的幸运数字。

我还有一个映射:

Map<String, Integer> wordToDigit = new HashMap<>();
map.put("two", 2);
map.put("three", 3);
map.put("four", 4);
map.put("five", 5);
map.put("six", 6);
map.put("eight", 8);

我需要将字符串中的单词替换为映射中相应的值。由于每个字符串并不包含映射中的所有键,所以如何在遍历字符串中的部分属性时更高效地完成,而不是遍历整个映射呢?

输出如下:

1. 是的,我有2、3、4个数字。
2. 我有5、6、7个字母。
3. 8、2、5是我的幸运数字。
英文:

I have strings like -

  1. yes, I have two, three, four numbers
  2. I have five, six, seven alphabets.
  3. eight, two, five are my lucky numbers.

and I also have Map

Map &lt;String, String&gt; wordToDigit = new HashMap&lt;&gt;;
Map.put(&quot;two&quot;, 2);
Map.put(&quot;three&quot;, 3);
Map.put(&quot;four&quot;, 4);
Map.put(&quot;five&quot;, 5);
Map.put(&quot;six&quot;, 6);
Map.put(&quot;eight&quot;,8);

I need to replace the words in a string with the corresponding value in the map.
As each string does not contain all the keys, stored in a map. So, How can I do it more efficiently by iterating over the attribute which is the part of the string and not iterate over whole map?

In output :-

1. yes, I have 2, 3, 4 numbers.
2. I have 5, 6, 7 alphabets.
3. 8, 2, 5 are my lucky numbers. 

答案1

得分: 1

我会将句子拆分成单词,然后重新构建句子,使用你的映射来检查每个单词是否有一个数字版本,并在有数字版本的情况下将其替换为该数字。

关键是要添加分隔符,因为标准的 String.split 方法不包括这些分隔符。

Map<String, Integer> wordToDigit = new HashMap<>();
wordToDigit.put("two", 2);
wordToDigit.put("three", 3);
wordToDigit.put("four", 4);
wordToDigit.put("five", 5);
wordToDigit.put("six", 6);
wordToDigit.put("eight", 8);

String sentence = "yes, I have two, three, four numbers";

String[] words = sentence.split("[^a-zA-Z]+", -1);

int pos = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
    int idx = sentence.indexOf(word, pos);
    String delim = sentence.substring(pos, idx);
    sb.append(delim);

    Integer n = wordToDigit.get(word.toLowerCase());
    sb.append(n == null ? word : n);

    pos += delim.length() + word.length();
}
sb.append(sentence.substring(pos, sentence.length()));

System.out.println(sb);

输出:

yes, I have 2, 3, 4 numbers

对于其他两个句子:

I have 5, 6, seven alphabets
8, 2, 5 are my lucky numbers.
英文:

I would split the sentence up into words and then rebuild the sentence, using your map to check if each word has a numeric version, and if it does using that in place of the word.

The trick is to add the delimiters back in, as these aren't included by the standard String.split method.

Map &lt;String, Integer&gt; wordToDigit = new HashMap&lt;&gt;();
wordToDigit.put(&quot;two&quot;, 2);
wordToDigit.put(&quot;three&quot;, 3);
wordToDigit.put(&quot;four&quot;, 4);
wordToDigit.put(&quot;five&quot;, 5);
wordToDigit.put(&quot;six&quot;, 6);
wordToDigit.put(&quot;eight&quot;,8);	

String sentence = &quot;yes, I have two, three, four numbers&quot;;

String[] words = sentence.split(&quot;[^a-zA-Z]+&quot;, -1);

int pos = 0;
StringBuilder sb = new StringBuilder();
for(String word : words)
{
	int idx = sentence.indexOf(word, pos);
	String delim = sentence.substring(pos, idx);
	sb.append(delim);        

	Integer n = wordToDigit.get(word.toLowerCase());
	sb.append(n == null ? word : n);
	
	pos += delim.length() + word.length();	  	
}
sb.append(sentence.substring(pos, sentence.length()));        

System.out.println(sb);

Output:

yes, I have 2, 3, 4 numbers

and for the other 2 sentences

I have 5, 6, seven alphabets
8, 2, 5 are my lucky numbers.

答案2

得分: 1

以下是两种不同的实现:(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 {
        // 测试
        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.

两种实现的逻辑都很简单。

英文:

Given below are two different implementations: (1) Using Map (2) Using List and array:

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 = { &quot;yes, I have two, three, four numbers.&quot;, &quot;I have five, six, seven alphabets.&quot;,
&quot;eight, two, five are my lucky numbers.&quot;, &quot;Someone gave him FIVE canines and asked him to feed two.&quot; };
System.out.println(&quot;Using Map: &quot;);
for (String sentence : sentences) {
System.out.println(replaceWordsWithValue1(sentence));
}
System.out.println(&quot;Using List and array: &quot;);
for (String sentence : sentences) {
System.out.println(replaceWordsWithValue2(sentence));
}
}
static String replaceWordsWithValue1(String str) {
Map&lt;String, String&gt; wordToDigit = Map.of(&quot;two&quot;, &quot;2&quot;, &quot;three&quot;, &quot;3&quot;, &quot;four&quot;, &quot;4&quot;, &quot;five&quot;, &quot;5&quot;, &quot;six&quot;, &quot;6&quot;,
&quot;seven&quot;, &quot;7&quot;, &quot;eight&quot;, &quot;8&quot;, &quot;nine&quot;, &quot;9&quot;);
for (String key : wordToDigit.keySet()) {
Pattern pattern = Pattern.compile(&quot;\\b&quot; + Pattern.quote(key) + &quot;\\b&quot;, 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 = { &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot; };
List&lt;String&gt; keys = List.of(&quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;);
for (String key : keys) {
Pattern pattern = Pattern.compile(&quot;\\b&quot; + Pattern.quote(key) + &quot;\\b&quot;, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = str.replaceAll(matcher.group(), values[keys.indexOf(key)]);
}
}
return str;
}
}

Output:

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.

The logic in both the implementations is straightforward.

huangapple
  • 本文由 发表于 2020年4月7日 03:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61067087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定