如何使用尽可能多的重复字符排列两个char数组?这就是我得到的。
public class Repeat {
public static void main(String[] args) {
String Foo = "HELLO";
String Boo = "VEX";
char [] Key = new char[Foo.length()];
for(int i = 0; i < Foo.length(); i++) {
for(int j = 0; j < Key.length; j++) {
if(i < Boo.length()) {
Key[i] = Boo.charAt(i);
}
}
}
for(char c : Key) {
System.out.print(c + " ");
}
}
}
目前打印出V E X [ ] [ ]
我希望密钥打印出来
V E X V E
所以它与
对齐H E L L O
答案 0 :(得分:2)
我不知道为什么人们可能想要这样做,但你可以使用模运算符%
以及更短和更长的字符串长度来实现你想要做的事情。像这样:
String longString = "abcde";
String shortString = "abc";
char[] array = new char[longString.length()];
for(int i = 0; i < array.length(); i++) {
array[i] = shortString.charAt(i % shortString.length());
}
如果您输出array
的内容,则应获得abcab
。
for
循环从0迭代到array
的长度(等于longString.length()
)减1.这确保了数组的所有元素(0,1,... ,array.length() - 1
)可以在循环体中初始化。
语句i % shortString.length()
确定应从shortString
检索的字符的位置。由于i
可能大于或等于shortString.length()
(如果用作shortString.charAt(int)
的参数会导致异常),您必须添加模运算符,以确保参数为shortString.charAt(int)
shortString.length()
保持在从0(包括)到SELECT r.rid
, r.no_of_persons
, COUNT(p.rid) AS no_allocated
FROM room_detail r
LEFT
JOIN allocated_user p
ON p.rid = r.rid
GROUP
BY r.rid
, r.no_of_persons
(不包括)的范围内,但会导致在每次迭代中返回另一个字符。
答案 1 :(得分:1)
这是一个解决方案,它允许您在不使用显式循环的情况下构建输出String
:
public static void main(String[] args) {
String foo = "HELLO";
String boo = "VEX";
String repeated = new String(new char[foo.length() / boo.length()]).replace("\0", boo);
repeated += boo.substring(0, foo.length() % boo.length());
repeated = repeated.replace("", " ").trim();
System.out.println(repeated);
}
<强>输出:强>
V E X V E
答案 2 :(得分:1)
这是一种为无限数量的字符串重复打印的方法:
private static void printRepeatedToLongest(String ... values) {
int maxLen = 0;
for (String value : values)
if (value.length() > maxLen)
maxLen = value.length();
for (String value : values)
if (value.length() == maxLen)
System.out.println(value);
else {
char[] buf = new char[maxLen];
for (int i = 0, len; i < maxLen; i += len) {
len = Math.min(value.length(), maxLen - i);
value.getChars(0, len, buf, i);
}
System.out.println(buf);
}
}
测试
public static void main(String[] args) {
printRepeatedToLongest(); // Prints nothing
printRepeatedToLongest(""); // Prints a blank line
printRepeatedToLongest("FOO"); // Prints the string
printRepeatedToLongest("HELLO", "VEX");
printRepeatedToLongest("recondite", "injure", "earthy", "taste", "calm", "minute",
"jealous", "level", "intend", "infamous", "men", "defeated");
}
输出
<-- blank line
FOO
HELLO
VEXVE
recondite
injureinj
earthyear
tastetast
calmcalmc
minutemin
jealousje
levelleve
intendint
infamousi
menmenmen
defeatedd