重复 Java 中的字符串以达到一定长度

Repeating Strings in Java to reach a certain length

我正在编写一个程序来使用关键字加密短语。首先,将要求用户输入他们选择的关键字。然后他们将被要求输入他们想要加密的短语。我遇到的问题如下:

如果用户的关键字是:你好 他们的加密短语是:再见

必须迭代关键字,以便加密的完整词 'goodbye' 可以被加密。例如:

hellohe
goodbye

如何迭代字符串以便仅再次迭代 'h' 和 'e'?

String keyword = "hello";
String phrase = "goodbye";
for (int i = 0; i < phrase.length(); i++) {
    char p = phrase.charAt(i);
    char k = keyword.charAt(i % keyword.length());
    System.out.println(p + " + " + k + " = " + (char)((p-'a' + k-'a')%26+'a'));
}

输出

g + h = n
o + e = s
o + l = z
d + l = o
b + o = p
y + h = f
e + e = i

当您为 "goodbye" 的每个字母加密时,检查您的加密密钥的长度 "hello"。

仅供参考,如果您的加密文本只是添加 msgkey:

for(int x=0; x<msg.length(); x++)
    encryptedChar = msg.charAt(x) + key.charAt(x % key.length());

来自第三方的 StringUtils class 方法 Apache Commons Lang has the rightPad 完全符合您的需求

你可以像这样使用它

String myword = StringUtils.rightPad("hello", "goodbye".length(), "hello");