在字符串中找到重复的子字符串

时间:2015-10-02 00:23:51

标签: vb.net visual-studio-2012

我正在尝试编写一个程序,用于查找和计算visual basic中重复序列中的字符数。

例如,字符串是: - ABCCCCCDEFFF

预期产出: -

C = 5

F = 3

2 个答案:

答案 0 :(得分:1)

我认为,为了学习一点编程,你会没事的。您的问题有一个简单的解决方案,您必须努力了解正在发生的事情。

<强>编辑:

Dim i, j, count As Integer
Dim str As String = "AAABCCCCCCDECCCFFF"
Dim myChar As Char
Dim listOfChars As New List(Of Char)
Dim listOfCount As New List(Of Integer)
Do While i < str.Length
    count = 0
    myChar = str.Chars(i)
    For j = i To str.Length - 1
        If Not str.Chars(j) = myChar Then
            listOfChars.Add(myChar)
            If count < 3 Then count = 0
            listOfCount.Add(count)
            Exit For
        ElseIf j = str.Length - 1 Then
            If str.Chars(j) = myChar Then count += 1
            listOfChars.Add(myChar)
            If count < 3 Then count = 0
            listOfCount.Add(count)
        End If
        count += 1
    Next
    If j = str.Length Then Exit Do
    i = j
Loop
For i = 0 To listOfChars.Count - 1
    Console.WriteLine("{0} = {1}", listOfChars(i), listOfCount(i))
Next

<强>输出:

A = 3
B = 0
C = 6
D = 0
E = 0
C = 3
F = 3

ElseIf添加的最后一句话根本不优雅,但它可以正常工作并处理Array index out of bound例外。

答案 1 :(得分:0)

我认为这应该有用......你可以随意格式化输出

Function getInfo(str as String)
     If str = "" Then
         return Nothing
     End If
     dim ret as String = ""
     dim current as string = str.First
     dim count as integer = 0
     For Each s in str
         If current = s Then
            count &= 1
         Else
            ret &= current & " = " & count & " "
            count = 0
         End If
         current = s
     Next
End Function