1. 程式人生 > >String類的幾種常用的方法

String類的幾種常用的方法

1.int length():獲取字串的長度

2.char charAt(int index):獲取指定的索引處的字串

3.int indexOf(String str):獲取str在字串物件中第一次出現的索引

4.String substring(int start):從start開始擷取字串

5.String substring(int start,int end):從start開始擷取字元,到end結束擷取字元

6.char[ ] toCharArray():把字串轉換為字元陣列;

7.String toLowerCase():把字串轉換為小寫字串

8.String toUpperCase():把字串轉換為小寫字串

6.程式碼實現鍵盤錄入字元資料,判斷大小寫和數字的個數:


        //1.鍵盤錄入
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入一個字串:");
        String s = sc.nextLine();
        //2.定義三個初始化值,用來接收字元判斷的各型別資料個數
        int dx=0;
        int xx=0;
        int number=0;
        //3.遍歷錄入的字串大小寫和數字的個數
        for(int i=0;i<s.length();i++) {
            char ch=s.charAt(i);
        //4.判斷遍歷的字元屬性
            if(ch>='A'&&ch<='Z') {
                dx++;
            }else if(ch>='a'&&ch<='z') {
                xx++;
            }else if(ch>='0'&&ch<='9'){
                number++;
            }
            else {
                System.out.println("非法字元:"+ch+"非法");
            }
        }
        System.out.println("大寫字元有:"+dx+"小寫字元有:"+xx+"數字有:"+number);