您可以使用 String.Split 和 String.Join 方法。既然您提到每行有一个值,我假设您正在从文件中读取并具有标准的 Windows CRLF 结尾。第一个拆分删除了行尾,然后我将它重新连接在一起,这样你就有了一串只有 1 和 0 的字符串。然后我在零上拆分,这将为您提供一个只有一个的数组。那时,它就像在每个 Array 元素上使用 String.Length 方法来获取每个字符串中的总数一样简单。如果您想将信息写回源(我假设是一个文件)将要求您遍历字符串并计算那些,然后将小计附加到现有字符串并将其写回文件。
Module Module1
Sub Main()
Dim splitFirst As String() = {vbCrLf}
Dim splitNext As String() = {"0"}
Dim testString As String = "1" & vbCrLf &
"1" & vbCrLf &
"1" & vbCrLf &
"0" & vbCrLf &
"0" & vbCrLf &
"0" & vbCrLf &
"1" & vbCrLf &
"1" & vbCrLf &
"1" & vbCrLf &
"1" & vbCrLf &
"0"
Dim results As String() = testString.Split(splitFirst, StringSplitOptions.RemoveEmptyEntries)
Dim holding As String = String.Join("", results)
results = holding.Split(splitNext, StringSplitOptions.RemoveEmptyEntries)
'Show the results
For Each item In results
Console.WriteLine(item & " Count = " & item.Length.ToString())
Next
Console.ReadLine()
End Sub
End Module
这与返回 a 的函数具有相同的想法,其中String Array
1 的组作为单个项目。
Public Function getColumnCounts(data As String) As String()
Dim splitFirst As String() = {vbCrLf} 'Seperator used to strip CrLf's
Dim splitNext As String() = {"0"} 'Seperator used to strip the 0's
'This is where the CrLf information is removed
Dim results As String() = data.Split(splitFirst, StringSplitOptions.RemoveEmptyEntries)
'Join the results array to make a string
Dim holding As String = String.Join("", results)
'Split it again to remove the blocks of zero's leaving just groups on ones in the array
results = holding.Split(splitNext, StringSplitOptions.RemoveEmptyEntries)
'Return the results as a String Array
'For Example
'For Each item In getColumnCounts(testString)
' Console.WriteLine(item & " Count = " & item.Length.ToString())
'Next
Return results
End Function