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循环)以及如何计算特定字符在字符串中出现的次数?

4

3 回答 3

20

答案很大程度上取决于您在课程作业中已经学到了什么以及您应该使用哪些功能。

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

Dim s As String = "test"

For Each c As Char in s
    ' Count c
Next

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

于 2012-11-06T12:47:35.170 回答
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
于 2012-11-06T12:50:27.433 回答
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)
于 2012-11-06T12:57:39.413 回答