首页 > 解决方案 > 如何使用循环将一串数组组合成一个字符串?

问题描述

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

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

谢谢

标签: javaarrays

解决方案


请尝试以下代码:-

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();
    }
}

推荐阅读