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

18

我正忙着准备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

我该如何使用 for 循环逐个遍历字符串中的字符,以及如何计算特定字符在字符串中出现的次数?

3个回答

20

答案在很大程度上取决于你在课程中已经学习了什么以及你应该使用哪些函数。

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

Dim s As String = "test"

For Each c As Char in s
    ' Count c
Next

关于计数,只需为每个字符设置单独的计数器变量(例如eCount As Integer),并在c等于该字符时将其递增 - 很明显,一旦您增加要计数的字符数量,这种方法就无法很好地扩展。可以通过维护相关字符的字典来解决此问题,但我猜想这对于您的练习来说可能太高级了。


谢谢Konrad,非常感谢你的建议。 - Timothy Coetzee
For Each 只能迭代集合对象或数组(VBA)。 - Anders Lindén
1
@AndersLindén 是的,但问题是关于VB.NET而不是VBA。 - Konrad Rudolph

2

遍历字符串很简单:一个字符串可以被视为字符列表,可以进行遍历。

Dim TestString = "ABCDEFGH"
for i = 0 to TestString.length-1
debug.print(teststring(i))
next

更简单的方法是使用for..each循环,但有时使用for i循环更好。

要计数,我会使用字典 像这样:

        Dim dict As New Dictionary(Of Char, Integer)
        dict.Add("e"c, 0)
Beware: a dictionary can only hold ONE item of the key - that means, adding another "e" would cause an error.
each time you encounter the char you want, call something like this:
        dict.Item("e"c) += 1

0

如果您被允许使用(或想要学习)Linq,您可以使用Enumerable.GroupBy

假设您的问题是您想要搜索的文本:

Dim text = "H*ow do i loop through individual characters in a string (using a for loop) and how do I count the number of times a specific character appears in a string?*"
Dim charGroups = From chr In text Group By chr Into Group

Dim eCount As Int32 = charGroups.Where(Function(g) g.chr = "e"c).Sum(Function(g) g.Group.Count)
Dim fCount As Int32 = charGroups.Where(Function(g) g.chr = "f"c).Sum(Function(g) g.Group.Count)
Dim gCount As Int32 = charGroups.Where(Function(g) g.chr = "g"c).Sum(Function(g) g.Group.Count)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接