VB运行时编码-For循环无法正确计数

时间:2018-11-29 08:30:50

标签: vb.net logic

我正在开发一个运行时编码程序。该程序应接收一个字符串,并计算一个字符串中一个字符出现的次数,每次出现一个不同字符时在一个新字符串中的数目和字符。但是,当我运行此命令时,第一个字符类型将被正确计数,然后其余字符将比它们应少的一个以及未添加的最后一个字符类型,例如

-+=Input your Data stream=+-
nnnMMMnnMn
3n2M1n0M

下面的代码:

Module Module1

Dim DataStream As String
Dim CompressedDataStream As String

Sub Main()

    RetrieveData()
    Console.WriteLine(CompressData(DataStream))
    Console.ReadLine()

End Sub

Sub RetrieveData()

    Console.WriteLine("-+=Input your Data stream=+-")
    DataStream = Console.ReadLine()

End Sub

Function CompressData(ByVal DataStream As String) As String

    Dim LengthOfDataStream As Integer = Len(DataStream)
    Dim tempChar As Char 'to store previous character
    Dim tempInt As Integer = 0 'to store number of occurences of character

    For iter = 0 To (LengthOfDataStream - 1)

        'check first character, store character
        'check next character if same character add one to tempInt

        If iter = 0 Then
            tempChar = DataStream(iter)
        Else
            tempChar = DataStream(iter - 1)
        End If

        If tempChar = DataStream(iter) Then
            tempInt = tempInt + 1
        Else
            CompressedDataStream = CompressedDataStream & tempInt & tempChar
            tempChar = String.Empty
            tempInt = 0
        End If

    Next

    Return CompressedDataStream

End Function

End Module

任何帮助将不胜感激,包括实现同一解决方案的不同方法。

3 个答案:

答案 0 :(得分:0)

如果可能存在大量字符,则忽略了可能应该使用StringBuilder的事实,这就是我倾向于这样做的方式:

Function CompressData(text As String) As String
    Dim output = String.Empty
    Dim previousChar = text(0)
    Dim count = 1

    For i = 1 To text.Length - 1
        Dim ch = text(i)

        If ch = previousChar Then
            count += 1
        Else
            output &= count & previousChar

            previousChar = ch
            count = 1
        End If
    Next

    Return output
End Function

答案 1 :(得分:0)

在您的函数和jmcilhinneys函数中,最后一个计数和char都丢失了,因为它没有在循环后 后附加。

array([0.29289   , 0.36136267, 0.6205081 ])

答案 2 :(得分:0)

您可以使用LINQString Interpolation来做到这一点:

Module Module1
  Sub Main()
    Dim oOutput As IEnumerable(Of IGrouping(Of Char, Char))
    Dim aOutput As String()

    Dim _
      sOutput,
      sInput As String

    sInput = "nnnMMMnnMn"
    oOutput = sInput.GroupBy(Function(Chr) Chr)
    aOutput = oOutput.Select(Function(Group) $"{Group.Count}{Group.Key}").ToArray
    sOutput = Join(aOutput, String.Empty)

    Console.WriteLine($"Input: {sInput}")
    Console.WriteLine($"Output: {sOutput}")

    Console.ReadKey()
  End Sub
End Module