This works:
for (char c : sourceString.toCharArray())
destString += (char) (c + shiftValue);
System.out.println(destString);
Is there a better/faster (optimized) way?
This works: for (char c : sourceString. toCharArray()) destString += (char) (c + shiftValue); System. out.
1. Using indexOf() and lastIndexOf() method. The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With