[英]Having trouble with an algorithm that loops through a string
我正在使用Visual Studio社區。
嗨,我寫了一個循環遍歷一系列彩票圖紙的循環,我想抓完整張圖紙並剪下日期,圖紙和強力球號碼。
第一次循環運行一切正常,我得到06/29/2002 04 33 35 36 45 Powerball: 22
,但是第二次循環獲得07/03/2002“ 04 33 35 36 45”強力球: 22。
第二次遍歷循環,返回到第一個圖形的編號。 我知道我會寫
Numbers(i) = Full_History.Substring(Start + 10, 16)
和Balls(i) = FullHistory.Substring(Start + 26, 14)
,但這似乎不對。 我希望我能解釋這個權利。 任何幫助將不勝感激。
Dim Start As Integer = 0 'Create a variable for start
Dim Finish As Integer = 40
For i As Integer = 0 To Array_Size - 1 Step 1 'Loop through the string
Full_Draw(i) = Full_History.Substring(Start, Finish) 'Store the full drawing
Dates(i) = Full_History.Substring(Start, 10) 'Store the Date of the drawing
Numbers(i) = Full_History.Substring(10, 16) 'Store the numbers drawn
Balls(i) = Full_History.Substring(26, 14) 'Store the 'ball' if necessary
Start += 40 'Increment the start variable
如果您有這樣的專用文本,則可以使用正則表達式提取數據,如以下代碼段所示:
Dim rx As New System.Text.RegularExpressions.Regex("(\d\d\/\d\d\/\d{4})\s(\d\d)\s(\d\d)\s(\d\d)\s(\d\d)\s(\d\d)\s+Powerball:\s(\d\d)")
Dim s = "06/29/2002 04 33 35 36 45 Powerball: 22 06/29/2002 04 33 35 36 45 Powerball: 22 06/29/2002 04 33 35 36 45 Powerball: 22 06/29/2002 04 33 35 36 45 Powerball: 22 06/29/2002 04 33 35 36 45 Powerball: 22"
Dim matches = rx.Matches(s)
Dim sb As New System.Text.StringBuilder
For Each m As System.Text.RegularExpressions.Match In matches
sb.AppendLine("Date: " & m.Groups(1).Value)
sb.AppendLine("#1: " & m.Groups(2).Value)
sb.AppendLine("#2: " & m.Groups(3).Value)
sb.AppendLine("#3: " & m.Groups(4).Value)
sb.AppendLine("#4: " & m.Groups(5).Value)
sb.AppendLine("#5: " & m.Groups(6).Value)
sb.AppendLine("Powerball: " & m.Groups(7).Value)
sb.AppendLine()
Next
MessageBox.Show(sb.ToString)
盡管它不是有史以來最高級的RegEx,但是它應該很容易遵循:
因此,您可以在給定的文本中找到所有匹配項,並且可以通過對匹配項進行迭代來輕松提取所有子組。
對於您的一般問題:
Numbers(i) = Full_History.Substring(10, 16) 'Store the numbers drawn
Balls(i) = Full_History.Substring(26, 14)
這些行將始終在源字符串中裁剪相同的部分(例如,索引10到26)。 您還需要使用Start
變量來縮放Substring的開始部分,例如
Numbers(i) = Full_History.Substring(Start + 10, 16) 'Store the numbers drawn
Balls(i) = Full_History.Substring(Start + 26, 14)
否則,不必驚訝每個元素的結局相同。 為了避免更多的混亂,請先將整個內容裁剪掉,然后將這個新字符串分解成各個部分:
For i As Integer = 0 To Array_Size - 1 Step 1 'Loop through the string
Dim ThisDraw As String = Full_History.Substring(Start, Finish)
Full_Draw(i) = ThisDraw
'Notice the fixed indizes now
Dates(i) = ThisDraw.Substring(0, 10) 'Store the Date of the drawing
Numbers(i) = ThisDraw.Substring(10, 16) 'Store the numbers drawn
Balls(i) = ThisDraw.Substring(26, 14) 'Store the 'ball' if necessary
Start += Finish
Next
謝謝你的回復。 我通過在數組中剪切單個圖形,然后在其中剪切出一個子字符串(單個圖形),而不是試圖直接從“ FullString”數組中剪切圖形,日期,數字和球,解決了該問題。流。
感謝Jim的所有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.