【问题标题】:How to combine a String of arrays to one string using loops? [duplicate]如何使用循环将一串数组组合成一个字符串? [复制]
【发布时间】:2020-10-30 10:01:19
【问题描述】:

我想通过循环将数组中的所有字符串组合成一个字符串。我该怎么做?

public class HelloWorld {

    public static void main(String[] args) {

        String [] x = {"ab", "bc", "cd"};

        String z = concatination(x, 3);

        System.out.println(z);
    }

    public static String concatination(String [] array, int i ){

        for(int j = 0; j<array.length-1; j++){
            return (array[j]);
        }
        return " ";
    }
}
output: 
java unreachable statement

Expected output:
abbccd

谢谢

【问题讨论】:

    标签: java arrays


    【解决方案1】:
    public static void main(String[] args) {
    
        String [] x = {"ab", "bc", "cd"};
    
        String z = concatination(x);
    
        System.out.println(z);
    }
    
    public static String concatination(String[] array) {
        String concat = "";
        for(int j = 0; j<array.length; j++) {
            concat += array[j];
        }
        return concat;
    }
    

    输出: abbccd

    【讨论】:

    • 一个好的答案应该可以解释问题。对你来说显而易见的事情对其他人来说可能并非如此。
    • @JohnnyMopp,好的,感谢您的反馈。我还是新来的。
    • @Ridwan 谢谢!你如何对字符做同样的事情?
    • @Priya,它会是一样的。
    【解决方案2】:

    请尝试以下代码:-

    public class HelloWorld{
    
         public static void main(String []args){
            String [] x = {"ab", "bc", "cd"};
            
            String z = concatination(x, 3);
    
            //With loop
            System.out.println(z);
            //Without loop
            System.out.println(String.join("",x));
         }
    
        public static String concatination(String [] array, int i ){
            StringBuilder builder = new StringBuilder();
            for(int j = 0; j<array.length; j++){
                builder.append(array[j]);
            }
            return builder.toString();
        }
    }
    

    【讨论】:

    • String z = concatination(x, 3); 当你不打算使用它时,为什么要传递3 作为参数。
    • 无需通过 3. 只需复制给定的代码 :-)
    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2011-04-30
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多