String和StringBuffer的幾個小程式

素鳶半暖畫涼箏發表於2020-11-15
1、//把陣列拼接成一個字串
public class StringBufferDemo3 {
    public static void main(String[] args) {
        int[] arr={1,2,3};
        String str="";
        str=str+"[";
        String result="";
        result=arrayToString(arr);
        str+=result;
        System.out.println(str);
        String str1="";
        str1=str1+"[";
        String result1="";
        result1=arrayToString1(arr);
        str1+=result1;
        System.out.println(str1);
    }
    public static String arrayToString(int [] arr){
        String s="";
        for(int i=0;i<=arr.length-1;i++){
            if (i==arr.length-1){
                s+=arr[i];
                s+="]";
            }else {
                s += arr[i];
                s += ",";
            }
        }
        return s;
    }
    public static String arrayToString1(int [] arr){
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<=arr.length-1;i++){
            if (i==arr.length-1){
                sb.append(arr[i]).append("]");

            }else {
                sb.append(arr[i]).append(",");
            }
        }
        return sb.toString();
    }
}

 

2、//把字串反轉
public class StringBufferDemo4 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入:");
        String str=sc.nextLine();
        char[]ch=str.toCharArray();
        String result=ResverString(ch);
        System.out.println(result);
        String result1=ResverString1(str);
        System.out.println(result1);
    }
    public static String ResverString(char[]ch){
        String s="";
        for(int i=ch.length-1;i>=0;i--){
            s+=ch[i];
        }
        return s;
    }
    public static String ResverString1(String s){
        StringBuffer sb=new StringBuffer(s);
        sb.reverse();
        return sb.toString();
    }
}
3、//判斷輸入的字元是否對稱
import java.util.Scanner;
public class StringBufferDemo5 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入:");
        String str=sc.nextLine();
        boolean result=isSelfSame(str);
        System.out.println(result);
        boolean result1=isSelfSame1(str);
        System.out.println(result1);
    }
    public static boolean isSelfSame(String s){
        char[] ch=s.toCharArray();
        boolean flag=true;
        for(int start=0,end=ch.length-1;start<=end;start++,end--){
            if(ch[start]!=ch[end]){
                flag=false;
            }else{
                flag=true;
            }
        }
        return flag;
    }
    public static boolean isSelfSame1(String s){
        return new StringBuffer(s).reverse().toString().equals(s);
    }
}

相關文章