循环字符串并计算列小计vb net 2010

时间:2013-09-28 02:07:45

标签: asp.net vb.net

我有一个每行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'到显示当前小计。

不太确定如何做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以使用String.Split和String.Join方法。既然你提到你每行有一个值我假设你正在读取一个文件并且有标准的Windows CRLF结尾。第一个Split删除了行结尾,然后我将它连接在一起,所以你有一个只有1和0的字符串。然后我在零上拆分,它会给你一个只有其中一个的数组。此时,它就像在每个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