2012-11-06 51 views
12

我忙於準備過去的考試試卷以準備Visual Basic考試。我需要幫助解決以下問題。在VB.NET中遍歷字符串中的字符

寫一個函數的過程來計算的次數「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環路),如何計算特定字符在字符串中出現的次數?

回答

12

答案很大程度上取決於您在課程中學到了什麼,以及您應該使用哪些功能。

但在一般情況下,循環在字符串中的字符是因爲這很容易:

Dim s As String = "test" 

For Each c As Char in s 
    ' Count c 
Next 

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

+0

感謝名單康拉德非常感謝您的輸入 –

1

在一個字符串中循環很簡單:一個字符串可以被當作一個可以循環的字符列表。

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

更容易將是一個for..each循環,但有時對於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)