最近学String,讲到了一些例子,记录一下吧。(后续把py的补上)
视频地址:https://www.bilibili.com/video/av49438855
需求:把数组 int [] arr={1,2,3}; 拼接成字符串[1,2,3]
Java
StringBuilder
public class StringBuilderExample02 {
public static void main(String[] args) {
int [] arr={1,2,3};
String s= arrayToString(arr);
System.out.println(s);//[1, 2, 3]
}
// 写方法实现拼接
// 返回值类型:String 参数列表 int[] arr
public static String arrayToString(int[] arr){
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i=0;i<arr.length;i++){
if(i==arr.length-1){
sb.append(arr[i]);
}else {
sb.append(arr[i]).append(", ");
}
}
sb.append("]");
String result = sb.toString();
return result;
}
}
String
public class StringExample05 {
public static void main(String[] args) {
int [] arr={1,2,3};
String s= arrayToString(arr);
System.out.println("s:"+s);
}
public static String arrayToString(int[] a) {
String s = "";
s += "[";
for (int i = 0; i < a.length; i++) {
if (i == a.length - 1) {
s += a[i];
} else {
s += a[i];
s += ", ";
}
}
s += "]";
return s;
}
}
网友评论