Kotlin程式:統計句子中母音和子音的個數


在這篇文章中,我們將學習如何在Kotlin中統計母音和子音的個數。包含以下字母的字母被稱為母音:

‘a’ ‘e’ ‘i’ ‘o’ ‘u’

所有其他字母被稱為子音。

假設我們的輸入是:

Hello, my name is Charlie

期望輸出:

The number of vowels in the statement is: 8
The number of vowels in the Consonants is: 12

演算法

  • 步驟1 - 開始

  • 步驟2 - 宣告兩個整數:vowelsCount,consonantsCount和一個字串input

  • 步驟3 - 定義值

  • 步驟4 - 執行for迴圈,檢查每個字母是子音還是母音。增加相應的整數。儲存值。

  • 步驟5 - 顯示結果

  • 步驟6 - 結束

示例1

在這個例子中,我們將使用for迴圈來統計句子中母音和子音的個數。首先,宣告並設定輸入字串

var myInput = "Hello, my name is Charlie"

現在,設定母音和子音的變數,並初始化為零

var vowelsCount = 0
var consonantsCount = 0

統計母音和子音

myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } }

現在讓我們看看使用for迴圈統計母音和子音個數的完整示例

fun main() { var myInput = "Hello, my name is Charlie" var vowelsCount = 0 var consonantsCount = 0 println("The statement is defined as: $myInput ") myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } } println("The vowel count is: $vowelsCount") println("The consonants count is: $consonantsCount") }

輸出

The statement is defined as: Hello, my name is Charlie
The vowel count is: 8
The consonants count is: 12

示例2

在這個例子中,我們將統計句子中母音和子音的個數:

fun main() { var myInput = "Hello, my name is Charlie" println("The statement is defined as: $myInput ") count(myInput) } fun count(input: String) { var myInput = input var vowelsCount = 0 var consonantsCount = 0 myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } } println("The vowel count is: $vowelsCount") println("The consonants count is: $consonantsCount") }

輸出

The statement is defined as: Hello, my name is Charlie
The vowel count is: 8
The consonants count is: 12

更新於:2022年10月13日

773 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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