public static String encode(String str) {if(str == null) {return null;}str = str.replace('+', '~');str = str.replace('/', '_');str = str.replace('=', '.');return str;}public static String encode2(String str) {if(str == null) {return null;}str = str.replace("+", "~");str = str.replace("/", "_");str = str.replace("=", ".");return str;}public static String encode3(String str) {if(str == null) {return null;}char[] array = str.toCharArray();for (int i = 0, length = array.length; i < length; i++) {if(array[i] == '+') {array[i] = '~';} else if(array[i] == '/') {array[i] = '_';} else if(array[i] == '=') {array[i] = '.';}}return new String(array);}
If you write three methods, the three methods can achieve character replacement, but the efficiency is different. The first and second methods are all traversal three times, and the third method is traversal;
The test string is:
String STR = "asdasddasd + ASD/asdadas ===== asdasd ++ // === kkkklakdjfh ";
Execute 1000000 times and the result is:
3031
51706
1401
The third array has the highest efficiency;
The test string is:
String STR = "asdasddasdasddasdasddasdasddasdasddasdasddasdasddasdasddasdasddasd ";
Execute 1000000 times and the result is:
1169
22874
1496
The first replace is more efficient.
The reason is that the replace method will first find whether the string contains the characters to be replaced. If it does not exist, it will be returned directly, and then it will traverse and replace (below is the replace source code, if you are interested, you can see). So when the target string does not contain the characters to be replaced, replace is the most efficient;
In daily development, you just need to call replace directly.
public String replace(char oldChar, char newChar) {if (oldChar != newChar) { int len = count; int i = -1; char[] val = value; /* avoid getfield opcode */ int off = offset; /* avoid getfield opcode */ while (++i < len) {if (val[off + i] == oldChar) { break;} } if (i < len) {char buf[] = new char[len];for (int j = 0 ; j < i ; j++) { buf[j] = val[off+j];}while (i < len) { char c = val[off + i]; buf[i] = (c == oldChar) ? newChar : c; i++;}return new String(0, len, buf); }}return this; }