如何使用 Java 查詢給定字串中的母音?


你可以使用 charAt() 方法 讀取 字串 中的一個字元。要查詢給定字串中的母音,你需要將其中的每個字元與母音字母進行比較。

舉例

即時演示

public class FindingVowels {
   public static void main(String args[]) {

      String str = new String("Hi Welcome to Tutorialspoint");
      for(int i=0; i<str.length(); i++) {
         if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
            System.out.println("Given string contains "+str.charAt(i)+" at the index "+i);
         }
      }
   }
}

輸出

Given string contains i at the index 1 
Given string contains e at the index 4 
Given string contains o at the index 7 
Given string contains e at the index 9 
Given string contains o at the index 12 
Given string contains u at the index 15 
Given string contains o  at the index 17 
Given string contains i at the index 19 
Given string contains a at the index 20 
Given string contains o at the index 24 
Given string contains i at the index 25

更新日期:07-10-2023

32K+ 瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.