Java: Shift all character-codes inside a String by a constant value

Mir-Ismaili picture Mir-Ismaili · Dec 5, 2016 · Viewed 7.6k times · Source

This works:

for (char c : sourceString.toCharArray()) 
    destString += (char) (c + shiftValue);

System.out.println(destString);

Is there a better/faster (optimized) way?

Answer

Jon Skeet picture Jon Skeet · Dec 5, 2016

Well I'd avoid using repeated string concatenation, to start with. That's a very well known performance problem.

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

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);

(The answer using toCharArray and then overwriting each element is nice too, although I'd expect any performance differences to be small. You'd want to test it with your actual system if this is really performance-critical code. The main point is that both are O(N) approaches rather than O(N2).)

However, you should think about whether you really want to just shift - most exercises like this are more rotate than shift, e.g. if you start with A-Z, you should end up with A-Z as well... a shift value of 1 should change Z to A, not to "the Unicode character after Z" (which is [). That may not be a requirement in your case, but you should certainly consider it.