【问题标题】:Looping through characters in a string in VB.NET在 VB.NET 中循环遍历字符串中的字符
【发布时间】:2012-11-06 12:43:52
【问题描述】:

我正忙于写过去的试卷,为 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 循环)以及如何计算特定字符在字符串中出现的次数?

【问题讨论】:

    标签: vb.net string loops character


    【解决方案1】:

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

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

    Dim s As String = "test"
    
    For Each c As Char in s
        ' Count c
    Next
    

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

    【讨论】:

    • Thanx Konrad 非常感谢您的意见
    • For Each 只能遍历集合对象或数组 (VBA)。
    • @AndersLindén 是的,但问题是关于 VB.NET,而不是 VBA。
    【解决方案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
    

    【讨论】:

      【解决方案3】:

      如果你被允许使用(或者你想学习)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)
      

      【讨论】:

        猜你喜欢
        • 2016-01-24
        • 1970-01-01
        • 2018-10-19
        • 2020-02-16
        • 2014-09-19
        • 2023-03-23
        • 1970-01-01
        • 2022-01-16
        相关资源
        最近更新 更多