简体   繁体   English

创建一个由给定数组的所有其他字符组成的新字符串,并返回它

[英]Creating a new string made of every other character of a given array, and returns it

Need to create a method in which, given a string, a new string will be made and returned formed out of every other character in the original string.需要创建一个方法,在该方法中,给定一个字符串,将生成一个新字符串并返回由原始字符串中的每个其他字符组成。

public static String everyOther(String str) {
    String result = "";
    for (int i=0; i<A.length; i+=2){ 
        result = result + str.charAt(i);
    }
    System.out.println(result);

    return result;
}

public static void main(String[] args) {
    String G = "abcdefghijklmnopqrstuvwxyz";
    System.out.println(everyOther(G));
}

Your everyOther method should read你的everyOther方法应该阅读

public static String everyOther(String str) {
    String result = "";
    for (int i=0; i < str.length(); i+=2){ 
        result += str.charAt(i);
    }
    return result;
}

Your for loop was slightly off (see my comment on OP), and there is no need to print out your result ehre as you do that in your main function - unless ofcourse you wanted to print it out twice您的 for 循环有点偏离(请参阅我对 OP 的评论),并且无需像在主函数中那样打印结果 ehre - 除非您当然想打印两次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM