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 I F (array[i] = = '/') {
Array[i] = ' _ ';
} else if (array[i] = = ' = ') {
array[i] = '.
}
} return new String (array);
Written as above three methods, 3 methods can achieve the effect of character substitution, but the efficiency is not the same, the first, the second way is to traverse three times, the third kind of traversal;
The test string is:
String str = "ASDASDDASD+ASD/ASDADAS======ASDASD++++++++//===KKKKLAKDJFH";
Executed 1 million times, the result is:
3031
51706
1401
The third kind of array is the most efficient;
The test string is:
String str = "ASDASDDASDASDASDDASDASDASDDASDASDASDDASDASDASDDASDASDASDDASDASDASDDASD";
Executed 1 million times, the result is:
1169
22874
1496
The first replace has a higher efficiency.
The reason is that the Replace method first looks up whether the string contains characters that need to be replaced. If there is no direct return, there will be to traverse the replacement (the following is replace the source code, interested can look at); So when the target string does not contain the characters that need to be replaced, replace is the most efficient;
In the daily development, do not toss, directly call replace to deal with it.
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;
}