java数组、字符串拼接

1. 数组实现拼接
int[] arr ={11,22,33,44,55,66};
System.out.print("[");
for (int i = 0; i <arr.length ; i++) {
if (i==arr.length-1){
System.out.print(arr[i]);
}else {
System.out.print(arr[i]+", ");
}
}
System.out.println("]");


2. String实现字符串拼接
String[] arr={"11","22","33","44","55"};
String s="[";
for (int i = 0; i <arr.length ; i++) {
if (i==arr.length-1)
s+=arr[i];
else {
s+=arr[i]+", ";
}
}
s+="]";
System.out.println(s);
3. StringBuilder实现字符串拼接
String[] ss ={"11","12","13","14","15"};
StringBuilder s =new StringBuilder();
s.append("[");
for (int i = 0; i <ss.length ; i++) {
if (i==ss.length-1){
s.append(ss[i]);
}else {
s.append(ss[i]).append(", ");
}
}
s.append("]");
String s1 =s.toString();
System.out.println(s1);
4.数组实现反转
int[] arr={11,22,33,44,55,66};
for (int start=0,end=arr.length-1;start<=end;start++,end--){
int tmp = arr[start];
arr[start]=arr[end];
arr[end]=tmp;
}
System.out.print("[");
for (int i = 0; i <arr.length ; i++) {
if (i==arr.length-1){
System.out.print(arr[i]);
}
else {
System.out.print(arr[i]+", ");
}
}
System.out.println("]");
5. 字符串实现反转
Scanner sc =new Scanner(System.in);
System.out.println("请您输入字符串:");
String s = sc.nextLine();
String s1="";
for (int i = s.length()-1; i >=0 ; i--) {
s1+=s.charAt(i);
}
System.out.println(s1);
6.使用StringBuilder实现反转
Scanner sc =new Scanner(System.in);
System.out.println("请您输入字符串:");
String s = sc.nextLine();
StringBuilder s2 =new StringBuilder(s);
s2.reverse();
String s3=s2.toString();
System.out.println(s3);

    原文作者:沉醉学习、无法自拔
    原文地址: https://www.cnblogs.com/liweichao-you/p/java.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注