Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This works:

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

System.out.println(destString);

Is there a better/faster (optimized) way?

like image 625
Mir-Ismaili Avatar asked Dec 05 '16 07:12

Mir-Ismaili


People also ask

How do you move all characters in a string in Java?

This works: for (char c : sourceString. toCharArray()) destString += (char) (c + shiftValue); System. out.

How do you find all occurrences of a character in a string in Java?

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.


1 Answers

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.

like image 176
Jon Skeet Avatar answered Sep 27 '22 17:09

Jon Skeet