java - 尝试使用循环来处理备用数组

标签 java arrays string loops char

我正在尝试通过交替字母大小写来打印字符串。我希望 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/

相关文章:

java - 在 Azure 数据工厂中设置不带冒号的时间格式 (Java SimpleDateFormat)

java - 通过WebView.goBack执行url

java - 两个应用程序使用相同的 keystore 时,SSL握手异常

java - PMD 的数据流异常分析警告

python - 将 Python Numpy 数组转换为单个数组的数组

c# - 如何在此示例中使用列表

arrays - AngularJs ng-repeat 表中的二维数组,每个子数组一列

java - 如何更新方法中的值?

arrays - firebase 子值作为数组中的字符串来填充选择器 swift 3

c++ - 如何在 C++ 中从字符串中快速查找和子字符串化多个项目?