我正在尝试通过交替字母大小写来打印字符串。我希望 YourString
显示为 YoUrStRiNg
。我已经尝试了三件事,但我无法让循环按照我需要的方式工作。这是我到目前为止所拥有的:
//one attempt
String s = "yourString";
String x = "";
for (int i = 0; i < s.length(); i += 2) {
for (int j = 1; j < s.length(); j += 2) {
x += Character.toUpperCase(s.charAt(i));
x += Character.toLowerCase(s.charAt(j));
}
}
System.out.println(x);
//the desired result but not the ideal solution
String[] sArray = {"Your", "String"};
String f = "";
for (String n : sArray) {
f += n;
}
char[] c = f.toUpperCase().toCharArray();
char[] d = f.toLowerCase().toCharArray();
System.out.print(c[0]);
System.out.print(d[1]);
System.out.print(c[2]);
System.out.print(d[3]);
System.out.print(c[4]);
System.out.print(d[5]);
System.out.print(c[6]);
System.out.print(d[7]);
System.out.print(c[8]);
System.out.print(d[9]);
System.out.println();
//third attempt with loop but the first loop keeps starting from zero
String t = "";
for (int i = 0; i < c.length; i += 2) {
for (int j = 1; j < d.length; j += 2) {
t += Character.toUpperCase(c[i]);
t += Character.toLowerCase(d[j]);
}
System.out.print(t);
}
我做错了什么?
最佳答案
实际上,无需多次迭代 String 的元素。由于您需要更改字符的大小写,因此可以使用运算符 %
来计算迭代的位置。因此,例如,给定 c
作为当前字符串字符,操作将如下所示:
System.out.print(i % 2 == 0, (char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));
但是,您实际上可以利用 Java Stream 和 lambda 表达式,从而实现一个非常优雅的解决方案。
我将向您展示我的提案解决方案。唯一的问题是,您实际上无法拥有适当的循环变量,因为您在巴巴表达式中访问的变量必须是最终的或有效的最终,所以我使用了一种技巧。
这只是给您一个想法,您实际上可以个性化它,使其可重用,并根据您的意愿改进它:
public class MyStringTest {
public static void main(String args[]) {
String s = "yourString";
initializeCycleVariable();
s.chars().forEach(c ->
{System.out.print( MyStringTest.getAndIncrement() %2 == 0 ?
(char)Character.toUpperCase(c) :
(char)Character.toLowerCase(c));
});
}
private static int i = 0;
public initializeCycleVariable() { i = 0; }
public static int getAndIncrement() { return i++; }
}
这是输出:
YoUrStRiNg
关于java - 尝试使用循环来处理备用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67821188/