循环遍历VB.NET中的字符串中的字符

Tim*_*zee 16 vb.net string loops character

我正忙着准备过去的考试试卷,为Visual Basic考试做准备.我需要帮助解决以下问题.

编写一个函数程序来计算字符串"e","f"和"g"出现在字符串中的次数

我试着编写伪代码并提出以下内容.

Loop through each individual character in the string
If the character = "e","f" or "g" add 1 to number of characters
Exit loop 
Display total in messagebox
Run Code Online (Sandbox Code Playgroud)

如何循环字符串中的单个字符(使用for循环)以及如何计算特定字符在字符串中出现的次数?

Kon*_*lph 16

答案很大程度上取决于您在课程作业中学到的内容以及您应该使用的功能.

但一般来说,循环字符串中的字符就像这样简单:

Dim s As String = "test"

For Each c As Char in s
    ' Count c
Next
Run Code Online (Sandbox Code Playgroud)

至于计数,只需eCount As Integer为每个字符设置单独的计数器变量(等),并在c等于该字符时递增它们- 显然,一旦增加要计数的字符数,该方法就不能很好地扩展.这可以通过维护相关字符的字典来解决,但我猜这对于你的练习来说太先进了.