By use of Java.
This code works:
for (char c : sourceString.toCharArray()) {
destString += (char) (c + shiftValue);
}
System.out.println(destString);
Is there a better/faster (optimized) way?
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.
See more on this question at Stackoverflow