簡體   English   中英

循環遍歷VB.NET中的字符串中的字符

[英]Looping through characters in a string in VB.NET

我正忙着准備過去的考試試卷,為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循環)以及如何計算特定字符在字符串中出現的次數?

答案很大程度上取決於您在課程作業中學到的內容以及您應該使用的功能。

但一般來說,循環字符串中的字符就像這樣簡單:

Dim s As String = "test"

For Each c As Char in s
    ' Count c
Next

至於計數,只需為每個字符設置單獨的計數器變量( eCount As Integer等),並在c等於該字符時遞增它們 - 顯然,一旦增加要計數的字符數,該方法就不能很好地擴展。 這可以通過維護相關字符的字典來解決,但我猜這對於你的練習來說太先進了。

循環一個字符串很簡單:一個字符串可以被視為一個字符列表,可以循環。

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

如果你被允許使用(或者你想學習)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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM