'Why am I getting whitespaces in StringBuilder in Java?
I wrote a method that returns a rotated StringBuilder with a given key. However, although it is working fine, it's adding white spaces within the StringBuilder.
public static StringBuilder rotateCipher(String plain, int key) {
int keyTemp = key;
char[] rotatedChar = new char[plain.length()];
StringBuilder builder = new StringBuilder();
for (int i = 0; i < plain.length(); i++) {
rotatedChar[i] = plain.charAt(key);
key++;
if (key == plain.length()) {
builder.append(String.valueOf(rotatedChar));
builder.append(plain.substring(0, keyTemp + 1));
break;
}
}
return builder;
}
Output: nopqrstuvwxyz abcdefghijklmn
Solution 1:[1]
The reason for the whitespace is that the array rotatedChar does not have all it's elements filled. By default, a char[] contains only (char)0 elements.
When you call this method with the parameters "abcdefghijklmnopqrstuvwxyz", 13 then only the first 13 elements of rotatedChar get filled, then you hit the if-condition and break out of the loop. That means you have the remaining 13 elements left as 0s, which is a nonprintable character, so it appears as whitespace.
It's a bit hard to suggest which part to change here because as Gabe pointed out in the comments, the solution only requires 2 calls to substring.
If you really want to use loops, maybe this can be an approach:
for (int i = 0; i < plain.length(); i++) {
rotatedChar[i] = plain.charAt(key);
key++;
if (key == plain.length()) {
//this "restarts" taking chars from the beginning of the string
key = 0;
}
}
return String.valueOf(rotatedChar);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
