java - 如何使用循环将一串数组组合成一个字符串?
问题描述
我想通过循环将数组中的所有字符串组合成一个字符串。我该怎么做?
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
谢谢
解决方案
请尝试以下代码:-
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();
}
}
推荐阅读
- java - 如果我在输出中输入字母,java程序会崩溃,请帮助解决这个问题
- sql - 具有连接结果集的表函数的返回类型
- mongodb - mongodb从另一个集合中添加字段
- amazon-web-services - Terraform AWS Lambda CI/CD 与单独存储库中的函数代码
- javascript - URL.createObjectURL 在掩码 url 中无法正常工作
- python - 如何修复 TypeError:元音()缺少所需的位置参数:'filehandle'?
- javascript - 如何使 JSON 响应数据全局化:)
- python - 在mac环境下操作PyInstaller可执行文件时,无法引用Excel工作表
- c# - 碰撞不适用于 Unity 2D 中的标签
- c - 具有字符串顺序的二叉搜索树