【问题标题】:replaceFirst for character "`"replaceFirst 用于字符“`”
【发布时间】:2013-07-30 20:32:59
【问题描述】:

第一次来。我正在尝试编写一个程序,该程序从用户那里获取字符串输入并使用 replaceFirst 方法对其进行编码。除“`”(重音符号)外的所有字母和符号都能正确编码和解码。

例如当我输入

`12

我应该得到 28AABB 作为我的加密,但它给了我 BB8AA2

public class CryptoString {


public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException {

    String input = "";

    input = JOptionPane.showInputDialog(null, "Enter the string to be encrypted");
    JOptionPane.showMessageDialog(null, "The message " + input + " was encrypted to be "+ encrypt(input));



public static String encrypt (String s){
    String encryptThis = s.toLowerCase();
    String encryptThistemp = encryptThis;
    int encryptThislength = encryptThis.length();

    for (int i = 0; i < encryptThislength ; ++i){
        String test = encryptThistemp.substring(i, i + 1);
        //Took out all code with regard to all cases OTHER than "`" "1" and "2"
        //All other cases would have followed the same format, except with a different string replacement argument.
        if (test.equals("`")){
            encryptThis = encryptThis.replaceFirst("`" , "28");
        }
        else if (test.equals("1")){
            encryptThis = encryptThis.replaceFirst("1" , "AA");
        }
        else if (test.equals("2")){
            encryptThis = encryptThis.replaceFirst("2" , "BB");
        }
    }
}

我已尝试将转义字符放在重音前面,但是仍然无法正确编码。

【问题讨论】:

  • 你真的有没有ifelse吗?
  • 您的代码无法编译。发布您正在使用的真实代码会更有帮助。
  • 我删除了所有其他案例,只显示了这个特定案例。
  • 此外,encryptThis.replaceFirst("`", "28") 正确地将` 替换为"28"
  • 不清楚你的加密应该如何处理其他字符,你的else if 没有前面的if

标签: java replace escaping


【解决方案1】:

看看你的程序在每次循环迭代中是如何工作的:

    • i=0
    • encryptThis = '12(我用 ' 而不是 ` 以便于写这篇文章)
    • 现在您将 ' 替换为 28,这样它将变为 2812
    • i=1
    • 我们在位置 1 读取字符,它是1 所以
    • 我们将 1 替换为 AA 使 2812 -> 28AA2
    • i=2
    • 我们在位置2读取字符,它是2所以
    • 我们将 first 2 替换为 BB 使 2812 -> BB8AA2

尝试使用 Matcher 中的 appendReplacement java.util.regex 包中的类

public static String encrypt(String s) {
    Map<String, String> replacementMap = new HashMap<>();
    replacementMap.put("`", "28");
    replacementMap.put("1", "AA");
    replacementMap.put("2", "BB");

    Pattern p = Pattern.compile("[`12]"); //regex that will match ` or 1 or 2
    Matcher m = p.matcher(s);
    StringBuffer sb = new StringBuffer();

    while (m.find()){//we found one of `, 1, 2
        m.appendReplacement(sb, replacementMap.get(m.group()));
    }
    m.appendTail(sb);

    return sb.toString();
}

【讨论】:

    【解决方案2】:

    encryptThistemp.substring(i, i + 1);子串的第二个参数是长度,你确定要增加i吗?因为这意味着在第一次迭代之后 test 不会是 1 个字符长。这可能会甩掉您的其他情况我们看不到!

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2021-12-26
      • 2023-03-15
      • 1970-01-01
      • 2016-02-08
      • 2012-12-18
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多