Search code examples
regexvb.netstringstring-function

How to replace even character of words in a string with "dash" or "symbol"?


I am trying to extract words from a string, then replace the even characters with dash..(not include white space) to make a kind of hints for a word game. For example:

InputString="English Language"

OutputString = "#n#l#s# #a#g#a#e"

Currently, I use this code below:

Private Sub Hint()

    Dim InputString as string = "English Language"
    dim SubInput as string()
    SubInput=InputString.Split(" ")

    For i=0 to UBound(SubInput) 'run through all items in SubInput array

        For k=0 to SubInput(i).length-1 'run through all characters in one item 

        If k mod 2= 0 then 'Do the replacement if even characters found
                SubInput(i)=SubInput(i).Replace(SubInput(i).Chars(k),"#") 
        End If

        Next

    Next

    Dim OutputString=String.Join(" ",subInput(i))
    Msgbox(OutputString)

    End Sub

However, I got the message box showing this "

#n#l#s# #a###a#e

" The word: Language is wrongly replaced at character no (3)

Could you point out how to get it fixed?

Thank you very much ~


Solution

  • can you try this code.much simple to implement and understand

    Dim s As String = "English Language"
            Dim intcount As Integer = 0
            For Each c As Char In s
                If intcount Mod 2 = 0 and c <> "" Then
                    s = s.Remove(intcount, 1).Insert(intcount, "#")
                End If
                intcount += 1
            Next
     Return s
    

    hope this helps.