我有一个字符串,每行 1 个值。 我称之为ttl_count。
ttl_count看起来像这样
1
1
1
0
0
0
1
1
1
1
0
等
1 和 0
我想做的是运行"ttl_count"中的数字列,并将连续分组总计 1。 使用上面的例子:
1
1
1 >> 3
0
0
0
1
1
1
1 >> 4
0
在这里,我们看到 2 个连续的组,一个小计为 3,另一个为 4。 我想将每个计算的小计发送到另一个变量中以确定 MAX 值,以及变量中的最后一个条目是否为"1"以显示当前的小计。
不太确定如何做到这一点。
String.Split 和 String.Join 方法。既然你提到你每行有一个值,我假设你正在从文件中读取并具有标准的 Windows CRLF 结尾。第一个 Split 删除了行尾,然后我将其重新连接在一起,因此您有一个只有 1 和 0 的字符串。然后我拆分零,这将为您提供一个只有 1 的数组。此时,只需在每个 Array 元素上使用 String.Length 方法获取每个字符串中的 1 总数即可。 如果您想将信息写回源(我假设一个文件)将需要您遍历字符串并计算这些字符串,然后将小计附加到现有字符串并将其写回文件。
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
这与返回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