【问题标题】:Replacing a character in a string with another character from another string用另一个字符串中的另一个字符替换字符串中的一个字符
【发布时间】:2021-06-15 09:43:32
【问题描述】:

我试图最终用另一组字符串替换一个句子。但是我在尝试用另一个字符串的另一个字符替换字符串中的字符时遇到了障碍。

这是我目前所拥有的。

String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";

//swapping each char of 'sentence' with the chars in 'encode'
for (int i = 0; i < sentence.length(); i++) {
    int indexForEncode = letters.indexOf(sentence.charAt(i));
    sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
}

System.out.println(sentence);

这种替换字符的方式行不通。有人可以帮我吗?

【问题讨论】:

    标签: java string replace char


    【解决方案1】:

    原因

    sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
    

    不起作用的是Strings 不可变(即它们永远不会改变)。 所以,sentence.replace(...) 实际上并没有改变sentence;相反,它返回一个新的String。您需要写 sentence = sentence.replace(...) 以在 sentence 中捕获该结果。

    好的,字符串 101:类已解除 (;->)。

    现在说了这么多,您真的不想继续将您部分编码的sentence 重新分配给它自己,因为几乎可以肯定,您会发现自己重新编码您已经编码的sentence 字符.最好将sentence 保留其原始形式,同时构建编码字符串,一次一个字符,如下所示:

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < sentence.length(); i++){
        int indexForEncode = letters.indexOf(sentence.charAt(i));
        sb.append(indexForEncode != -1
                ? encode.charAt(indexForEncode)
                : sentence.charAt(i)
        );
    }
    sentence = sb.toString();
    

    【讨论】:

    • 嗨,非常感谢!这对我有用。我希望我能投票。但是,如果“句子”中的字符不是字母,是否有一篇文章可供我阅读?如果我有非字母字符,这会给我一个错误。
    • 我已经更新了代码来解决这个问题;也许你还在看旧版本。您可能想查看Javadoc for the indexOf method: 以了解我的修复背后的逻辑。
    【解决方案2】:

    我会使用如下的字符数组。对字符数组进行更改,然后使用String.valueOf 获取新版本的字符串。

    String letters = "abcdefghijklmnopqrstuvwxyz";
    String encode =  "kngcadsxbvfhjtiumylzqropwe";
    // the sentence that I want to encode
    String sentence = "hello, nice to meet you!";
    
    char[] chars = sentence.toCharArray();
    for (int i = 0; i < chars.length; i++){
        int indexForEncode = letters.indexOf(sentence.charAt(i));
        // if index is < 0, use original character, otherwise, encode.
        chars[i] = indexForEncode < 0 ? chars[i] : encode.charAt(indexForEncode);
    }
    System.out.println(String.valueOf(chars));
    

    打印

    xahhi, tbga zi jaaz wiq!
    

    【讨论】:

      【解决方案3】:

      您可以使用codePoints 方法迭代此字符串的字符,并将它们替换为另一个字符串中的字符(如果有)。

      Try it online!

      public static void main(String[] args) {
          String letters = "abcdefghijklmnopqrstuvwxyz";
          String encode = "kngcadsxbvfhjtiumylzqropwe";
      
          String sentence = "hello, nice to meet you!";
          String encoded = replaceCharacters(sentence, letters, encode);
          String decoded = replaceCharacters(encoded, encode, letters);
      
          System.out.println(encoded); // xahhi, tbga zi jaaz wiq!
          System.out.println(decoded); // hello, nice to meet you!
      }
      
      public static String replaceCharacters(String text, String from, String to) {
          // wrong cipher, return unencrypted string
          if (from.length() != to.length()) return text;
          // IntStream over the codepoints of this text string
          return text.codePoints()
                  // Stream<Character>
                  .mapToObj(ch -> (char) ch)
                  // encrypt characters
                  .map(ch -> {
                      // index of this character
                      int i = from.indexOf(ch);
                      // if not present, then leave it as it is,
                      // otherwise replace this character
                      return i < 0 ? ch : to.charAt(i);
                  }) // Stream<String>
                  .map(String::valueOf)
                  // concatenate into a single string
                  .collect(Collectors.joining());
      }
      

      另见:Implementation of the Caesar cipher

      【讨论】:

        猜你喜欢
        • 2013-12-03
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 2021-12-04
        • 2012-07-16
        • 1970-01-01
        • 2013-12-31
        • 2012-01-01
        相关资源
        最近更新 更多