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.