[英]How do I replace certain characters in a String without using .replace()?
I have to write a programme that encrypts and decrypts hidden messages. 我必须编写一个加密和解密隐藏消息的程序。 My problem is changing the alphabet. 我的问题是更改字母。 Originally I was going to use .replace() method, however, my teacher said we're not allowed to. 本来我将使用.replace()方法,但是,我的老师说我们不允许这样做。 The only methods we are allowed to do are, 我们唯一可以做的方法是,
.indexof();
.length();
.substring();
I have no idea how I'm supposed to do this. 我不知道我该怎么做。 For example, Apple would be &**$# but how can I do this without .replace(); 例如,Apple将是&** $#,但是如果没有.replace();我怎么做呢?
Below is the idea, can be optimised by yourself : 以下是想法,可以自己优化:
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;
}
Or can use the StringBuilder
with recursion: 或者可以将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();
}
I suggest you read source code of String.replace(char oldChar, char newChar)
to implement your own method. 我建议您阅读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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.