除了删除最后一个字符的方式之外,您的解决方案似乎是合理的 - 不要一次执行一个,只需使用 substring 或StringBuilder.setLength()
:
// Make sure we never have to expand...
StringBuilder builder = new StringBuilder(plainText.length() + key.length() - 1);
while (builder.length() < plainText.length()) {
builder.append(key);
}
builder.setLength(plainText.length());
String result = builder.toString();
或者只是将附加调用更改为仅获得正确的大小:
StringBuilder builder = new StringBuilder(plainText.length());
while (builder.length() < plainText.length()) {
builder.append(key.substring(0, Math.min(key.length(),
builder.length() - plainText.length()));
}
String result = builder.toString();
我个人更喜欢第一个 - 它更简单。