java遍历数组拼接字符串
时间: 2023-10-15 07:25:02 浏览: 129
在Java中,可以使用循环来遍历数组并拼接字符串。可以参考以下代码实例:
public class Main {
public static void main(String[] args) {
int[] no = new int[]{501, 101, 204, 102, 334};
String[] names = new String[]{"张城", "刘丽丽", "李国旺", "孟红霞", "贺宁"};
String[] classes = new String[]{"数学", "语文", "数学", "英语", "英语"};
StringBuilder sb = new StringBuilder();
sb.append("本次考试学生信息如下:\n");
for (int i = 0; i < no.length; i++) {
sb.append("学号:").append(no[i]).append("|姓名:").append(names[i]).append("|课程:").append(classes[i]).append("|班级:").append("初二(三)班\n");
}
System.out.println(sb.toString());
}
}
以上代码通过使用StringBuilder类来拼接字符串,遍历数组并将每个数组元素拼接到字符串中。在循环中,使用StringBuilder的append方法来添加每个元素和分隔符,最后使用toString方法将StringBuilder对象转换为字符串并打印出来。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Java字符串拼接(连接)](https://blog.csdn.net/m0_74309242/article/details/129742779)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [java 拼接字符串的方法](https://blog.csdn.net/qq_42751978/article/details/130260886)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文