1. 程式人生 > >java使用charAt()方法計算字串中的重複字元

java使用charAt()方法計算字串中的重複字元

charAt()方法介紹

    charAt() 方法用於返回指定索引處的字元。索引範圍為從 0 到 length() - 1。
    例如:str.next().charAt(0);//獲取字串str中的第1個字元
         str.next().charAt(9);//獲取字串str中的第10個字元

使用charAt()方法計算字串中的重複字元程式碼:

import java.util.Scanner;
public class Test {

     public static void main(String[] args){
    	 
    	 String str = "hhusfhshuhfu";
    	 System.out.println("原字元為:"+str);//輸出原字元
    	 
    	 Scanner sc = new Scanner(System.in);
    	 System.out.print("請輸入要查詢的字元:");
    	 char ch = sc.next().charAt(0);//取輸入字串的第一個字元
    	 sc.close();
         int i,sum=0;//sum使用者記錄出現的字元個數
    	 

    	 //使用charAt()方法計算重複字元
    	 for ( i = 0 ; i < str.length() ; i++){
    		 
    		if ( str.charAt(i) == ch )
    			++sum;//計數
    	         	 
    	 }
    	 
    	 System.out.print(str+"中出現"+ch+"的次數為"+sum+"次");//輸出
    	 
     }
   
}

執行結果:

原字元為:hhusfhshuhfu
請輸入要查詢的字元:s
hhusfhshuhfu中出現s的次數為2次