简体   繁体   English

为什么我在 Java 中的 StringBuilder 中出现空格?

[英]Why am I getting whitespaces in StringBuilder in Java?

I wrote a method that returns a rotated StringBuilder with a given key.我编写了一个方法,该方法返回具有给定键的旋转StringBuilder However, although it is working fine, it's adding white spaces within the StringBuilder .但是,尽管它工作正常,但它在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

The reason for the whitespace is that the array rotatedChar does not have all it's elements filled.空白的原因是数组rotatedChar没有填充它的所有元素。 By default, a char[] contains only (char)0 elements.默认情况下, char[]仅包含(char)0个元素。

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.当您使用参数"abcdefghijklmnopqrstuvwxyz", 13只会填充rotatedChar的前 13 个元素,然后您break遇到 if 条件并跳出循环。 That means you have the remaining 13 elements left as 0 s, which is a nonprintable character, so it appears as whitespace.这意味着您将剩余的 13 个元素保留为0 s,这是一个不可打印的字符,因此它显示为空白。

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 .在这里建议更改哪一部分有点困难,因为正如 Gabe 在评论中指出的那样,该解决方案只需要 2 次调用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM