JAVA 尋找「指定字元」出現在「指定字串」中的次數

2018/09/28 1,690 1 程式設計 , JAVA

這是一個 JAVA 程式的小練習,程式功能是尋找「指定字元」出現在「指定字串」中的次數,執行後的步驟如下:

一、顯示「Enter the characters to be detected (multiple, do not repeat):」字串。
二、使用者輸入「要列入檢測的字元(可多個,勿重複)」。
三、顯示「Enter the string to be detected:」字串。
四、使用者輸入「要被檢測的字串:」。
五、顯示執行結果「Detection result: 次數」

JAVA 程式碼如下:

import java.util.Scanner;
 
class toFindChar {
  public static void main(String[]gg){
    Scanner scanner = new Scanner(System.in);
    String J,S;
    System.out.println("Enter the characters to be detected (multiple, do not repeat):");
    J = scanner.nextLine();
    System.out.println("Enter the string to be detected:");
    S = scanner.nextLine();
    int output=0;
    for (int i=0;i<S.length();i++){
      for (int j=0;j<J.length();j++){
        if((int) S.charAt(i) == (int) J.charAt(j)){
          output++;
        }
      }
    }
    System.out.println("Detection result: "+output);
  }
}


▲程式碼與程式實際運作的截圖。

📝 筆記:利用 JAVA 可以取得字串中的每個字元(char),並強制轉型為整數(int)的資料型別,透過 ASCII 碼來比對是否一致,若一致將 output++ (+1的意思),我使用雙迴圈來偵測字元,最後輸出結果次數,此程式時間複雜度 Big-O 為 n^2,即 O(n^2)。

贊助廣告 ‧ Sponsor advertisements

留言區 / Comments

萌芽論壇