Shift all character codes within a string to a constant value

Using the Java .

This code works:

for (char c : sourceString.toCharArray()) {
    destString += (char) (c + shiftValue);
}
System.out.println(destString);

Is there a better / faster (optimized) way?

+4
source share
3 answers

Well, I would avoid using re-concatenation of strings , for starters. This is a very well known performance issue.

In this case, you know the exact length with which you need to start, so you don't even need to StringBuilder- a char[]in order:

char[] result = new char[srcString.length()];
for (int i = 0; i < result.length; i++) {
    result[i] = (char) (srcString.charAt(i) + shiftValue);
}
String destString = new String(result);

( toCharArray, , , . , . , O (N), O (N 2)).

, - , , , , . A-Z, A-Z... 1 Z A, " Unicode Z" ( [). , .

+7

. charAt(i) .

char[] result = srcString.toCharArray();
for (int i = 0; i < result.length; i++) {
    result[i] += shiftValue;
}
String destString = new String(result);
+6

, :

StringBuilder destString = new StringBuilder();
for (char c : srcString.toCharArray()) {
    destString.appned((char) (c + shiftValue));
}
System.out.println(destString.toString());
+1

Source: https://habr.com/ru/post/1662812/


All Articles