Java程式統計給定句子中母音的數量


給定一個句子(字串),例如str,計算其中母音的總數。在Java中,String是一種非原始資料型別,用於定義字元序列。並且,英文字母a、e、i、o和u被稱為母音

要計算給定句子中母音的數量,建立一個名為count的變數並將其初始化為0。將出現次數儲存在這個變數中。接下來,將句子中的每個字元與母音進行比較。如果匹配,則遞增計數並列印它。

統計母音數量

在Java中,我們可以透過以下方法計算給定句子中母音的數量:

  • 使用for迴圈
  • 使用switch語句
  • 使用正則表示式

使用for迴圈

定義一個for迴圈來迭代給定句子的每個字元,並在該迴圈內使用if塊來比較和計數母音。

示例

在這個例子中,我們使用for迴圈來計算給定句子中母音的數量。

public class CountingVowels {
   public static void main(String args[]) {
      int count = 0;
      String sentence = "welcome to tutorialspoint";

      for (int i = 0 ; i < sentence.length(); i++) {
         char ch = sentence.charAt(i);
         if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'|| ch == 'A'|| ch == 'E'|| ch == 'I'|| ch == 'O'|| ch == 'U') {
            count ++;
         }
      }
      System.out.println("Number of vowels in the given sentence: " + count);
   }
}

這段程式碼將產生以下結果:

Number of vowels in the given sentence: 10

使用switch語句

在這種方法中,使用switch語句將母音與給定句子的字元進行比較。當找到匹配項時,遞增計數並列印結果。

示例

在下面的例子中,我們使用switch語句計算給定句子中母音的數量。

public class CountingVowels {
   public static void main(String args[]) {
      int count = 0;
      String sentence = "How are you today";

      for (int i = 0; i < sentence.length(); i++) {
         char ch = sentence.charAt(i);
         switch (ch) {
            case 'a': case 'e': case 'i': case 'o': case 'u':
            case 'A': case 'E': case 'I': case 'O': case 'U':
               count++;
               break;
          }
      }
      System.out.println("Number of vowels in the given sentence: " + count);
   }
}

執行後,這段程式碼將產生以下結果:

Number of vowels in the given sentence: 7

使用正則表示式

在Java中,正則表示式(有時稱為regex)是定義搜尋模式的字元序列。java.util.regex包用於處理正則表示式。

要計算母音的數量,請使用母音建立一個Pattern物件,然後使用Matcher物件在輸入句子中查詢此模式的出現。

示例

下面的例子說明了如何使用正則表示式計算給定句子中母音的數量。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountingVowels {
   public static void main(String args[]) {
      int count = 0;
      String sentence = "Hi! Welcome to Tutorialspoint";
      Pattern myPattern = Pattern.compile("[aeiouAEIOU]");
      Matcher match = myPattern.matcher(sentence);
      while (match.find()) {
         count++;
      }
      System.out.println("Number of vowels in the given sentence: " + count);
   }
}

執行以上程式碼後,將顯示以下輸出:

Number of vowels in the given sentence: 11

更新於:2024年7月30日

29K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.