如何在不使用.replace()的情况下替换String中的某些字符?

时间:2018-04-16 01:40:23

标签: java string

我必须编写一个加密和解密隐藏消息的程序。我的问题是改变字母表。最初我打算使用.replace()方法,然而,我的老师说我们不允许这样做。我们被允许做的唯一方法是,

.indexof();
.length();
.substring();

我不知道我应该怎么做。例如,Apple将是& ** $#但是如果没有.replace();

我该怎么做呢

2 个答案:

答案 0 :(得分:2)

以下是这个想法,可以自己优化:

public String replace(String original, String toBeReplacedStr, String withStr) {
    while(true) {
      int i = original.indexOf(toBeReplacedStr);
      if (i == -1) {
         break;
      }
      original = original.substring(0, i) + withStr + original.substring(i + toBeReplacedStr.length());
    }
    return original;
}

或者可以将StringBuilder与递归一起使用:

public String replace(String original, String toBeReplacedStr, String withStr) {
    int i = original.indexOf(toBeReplacedStr);
    if (i < 0) {
      return original;
    }
    StringBuilder sb = new StringBuilder();
    String before = original.substring(0, i);

    String rawAfter  = original.substring(i + toBeReplacedStr.length());
    String replacedAfter = replace(rawAfter, toBeReplacedStr, withStr);
    return sb.append(before).append(withStr).append(replacedAfter).toString();
}

答案 1 :(得分:0)

我建议你阅读String.replace(char oldChar, char newChar)的源代码来实现自己的方法。

public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {
                if (val[i] == oldChar) { // comment 1, aims to find 
          // first index of oldChar. You can use indexOf() to achieve this.
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j]; // comment 2, copy prefix chars 
          // before the oldChar to buf. You can use subString() to achieve this.
                }
                while (i < len) {
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c; // comment 3, 
        // replace oldChar with newChar, for other chars, just copy. 
        // You can use the thought above. I suggest you divide to 3 
        // methods to do "replace" thing.
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }
相关问题