试图让循环通过交替数组工作

问题描述

我试图通过交替字母大小写来打印出一个字符串。我希望 YourStringYoUrStRiNg 的身份出现。我已经尝试了三件事,但我无法让循​​环按照我需要的方式工作。这是我到目前为止所拥有的:

//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 作为当前 String 字符,操作将是这样的:

System.out.print(i % 2 == 0,(char)Character.toUpperCase(c) : (char)Character.toLowerCase(c));

然而,您实际上可以利用 Java Stream 和 lambda 表达式的优势,从而实现一个非常优雅的解决方案。
我将向您展示我的建议解决方案。唯一的问题是你实际上不能有一个适当的循环变量,因为你在 Lamba 表达式中访问的变量必须是 final 或有效 final,所以我使用了一种技巧。
这只是给您一个想法,您实际上可以对其进行个性化、使其可重复使用并根据需要对其进行改进:

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
,

您应该逐个字符地遍历字符串。您可以对偶数索引使用大写,对奇数索引使用小写。很抱歉没有提供更多细节,但很明显这是一项作业。

,

试试这个,

String s = "yourString",x = "";
for(int i = 0; i < str.length(); i++){

    if(i % 2 == 0)
        x += Character.toUpperCase(s.charAt(i));
    else
        x += Character.toLowerCase(s.charAt(i));
}
System.out.println(x);