简体   繁体   中英

find repetitive substring within string

I am trying to write a program that finds and counts the number of characters in aa repetitive sequence in visual basic.

For example, the string is :- ABCCCCCDEFFF

Expected output:-

C = 5

F = 3

I think it will be fine for you in order to learn a little about programming. Your question has an easy solution, and you have to make an effort to understand what's happening.

Edited:

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

Output:

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

The last sentence ElseIf added is not elegant at all but it works fine and handles the Array index out of bound exception.

i think this should work ... You could format the output anyway you want

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM