【问题标题】:How to replace multiple String characters? [duplicate]如何替换多个字符串字符? [复制]
【发布时间】:2021-05-31 11:35:57
【问题描述】:

我有一个包含 6 个不同字符串的数组。现在我专注于用不同的字符替换数组第一句中的所有字母。例如,句子中的所有“r”都会变成“i”,所有“t”都会变成“u”。我在下面尝试的代码仅替换了我在最后一行编写的代码的字符。 (它将所有的 'p' 替换为 'u' 但忽略了上面的所有代码)

如何替换句子中的每个字符?

public static void replaceString(String[] arr) {
    
    String s1 = arr[0];
    for (String i: arr) {
        String sentence1 = s1.toLowerCase().replace("a", "t");
        sentence1 = s1.toLowerCase().replace("r", "m");
        sentence1 = s1.toLowerCase().replace("e", "i");
        sentence1 = s1.toLowerCase().replace("s", "n");
        sentence1 = s1.toLowerCase().replace("p", "u");
        System.out.println(sentence1);
    }
}

【问题讨论】:

  • 你需要重复使用你在第一行分配的String。我相信你会找到哪个:)
  • 为什么是循环? ...您遍历所有字符串,但从不使用它们? i 在很多层面上都被忽略了......并且句子打印了很多次......

标签: java


【解决方案1】:

你需要重用返回的字符串,否则你总是重写整个sentence1。记住字符串是不可变的。

String sentence1 = s1.toLowerCase().replace("a", "t");
sentence1 = sentence1.toLowerCase().replace("r", "m");
sentence1 = sentence1.toLowerCase().replace("e", "i");
sentence1 = sentence1.toLowerCase().replace("s", "n");
sentence1 = sentence1.toLowerCase().replace("p", "u");

...可以重写为:

String sentence1 = s1.toLowerCase()
                     .replace("a", "t")
                     .replace("r", "m");
                     .replace("e", "I");
                     .replace("s", "n");
                     .replace("p", "u");

【讨论】:

  • 为什么每次都需要重新小写?
  • 在这种情况下,你不需要。
【解决方案2】:

您可能会发现StringUtils.replaceChars() 是一种更好的方法:

sentence1 = StringUtils.replaceChars(s1.toLowerCase(), "aresp", "tminu");

添加 Apache 的 commons-lang3 库作为依赖项。

【讨论】:

  • 值得一提的是,这需要额外的依赖。对于这个用例可能不值得。
  • apache.commons.lang3 - 这是值得的。这就是答案。
【解决方案3】:

Strings 是不可变的。你不能就地修改它们,你总是必须创建一个新对象。

例子:

String s1 = "";
String s2 = s1 + "foo";
String s3 = s2.replace("foo", "bar");

s1 和 s2 不会改变,因为它们永远不会被重新分配。尽管这些变量的值保持不变:

System.out.println(s1); // ""
System.out.println(s2); // "foo"
System.out.println(s3); // "bar"

如果你想改变s1,你需要给它重新赋值:

String s1 = "";
s1 = s1 + "foo";
s1 = s1.replace("foo", "bar");

现在 s1 将是 "bar"

【讨论】:

    【解决方案4】:

    您可以编写一个文本替换器,通过根据Map 中的每个条目减少字符串来替换每个字符。您可以通过操作 StringBuilder 对象而不是普通的 String 来优化字符串替换。

    import java.util.*;
    import java.util.stream.Collectors;
    
    public class TextReplacer {
        private static final Map<String, String> replacements;
        private static final List<String> phrases;
    
        static {
            phrases = List.of("Hello World", "Do you like peppers?");
            replacements = new HashMap<String, String>() {{
                put("r", "m");
                put("e", "i");
                put("s", "n");
                put("p", "u");
            }};
        }
    
        public static void main(String[] args) {
            replaceAll(phrases, replacements).stream().forEach(System.out::println);
            replaceAllOptimized(phrases, replacements).stream().forEach(System.out::println);
        }
    
        public static String replace(String phrase, Map<String, String> replacements) {
            return replacements.entrySet().stream().reduce(phrase.toLowerCase(), (s, e) -> s.replace(e.getKey(), e.getValue()), (s1, s2) -> null);
        }
    
        public static List<String> replaceAll(List<String> phrases, Map<String, String> replacements) {
            return phrases.stream().map(s -> replace(s, replacements)).collect(Collectors.toList());
        }
    
        public static String replaceOptimized(String phrase, Map<String, String> replacements) {
            return replacements.entrySet().stream().reduce(new StringBuilder(phrase.toLowerCase()), (s, e) -> replaceAll(s, e.getKey(), e.getValue()), (s1, s2) -> null).toString();
        }
    
        public static List<String> replaceAllOptimized(List<String> phrases, Map<String, String> replacements) {
            return phrases.stream().map(s -> replaceOptimized(s, replacements)).collect(Collectors.toList());
        }
    
        public static StringBuilder replaceAll(StringBuilder builder, String from, String to) {
            int index = builder.indexOf(from);
            while (index != -1) {
                builder.replace(index, index + from.length(), to);
                index += to.length();
                index = builder.indexOf(from, index);
            }
            return builder;
        }
    }
    
    

    输出

    hillo womld
    do you liki uiuuimn?
    hillo womld
    do you liki uiuuimn?
    

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 2022-08-03
      • 2015-03-15
      • 2014-06-27
      • 2011-09-01
      • 1970-01-01
      相关资源
      最近更新 更多