关于Java中的数组转变成字符串问题

时间:2023-01-04 18:44:08

1。用StringBuilder

private 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("]");
			return sb.toString();
	    }

 2.普通型

private static void bianli(int arr[]){
	    	System.out.print("[");
	    	int i;
	    	for (i = 0; i < arr.length; i++) {
				if(i==arr.length-1){
					System.out.println(arr[i]+"]");
				}else {
					System.out.print(arr[i]+", ");
				}	    
			}
	    }

 3.字符串型

private static String arraytoString1(int arr[]){
	    	String s="";
	    	s+="[";
	    	for (int i = 0; i < arr.length; i++) {
				if(i==arr.length-1){
					s+=arr[i];
				}else {
					s+=arr[i];
					s+=", ";
				}	    
			}
	    	s+="]";
			return s;
	    }