java数组、字符串拼接

2019-11-14 16:06:51来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:linux 安装java

下一篇:java:线上问题排查常用手段