How to reverse only the alphabetic characters in a string, keeping other characters in place with VB.NET

1 Answer

0 votes
Imports System

Module Module1

    Function reverseOnlyAlphabeticCharacters(s As String) As String
        Dim chars() As Char = s.ToCharArray()
        Dim i As Integer = 0
        Dim j As Integer = chars.Length - 1

        While i < j
            If Not Char.IsLetter(chars(i)) Then
                i += 1
            ElseIf Not Char.IsLetter(chars(j)) Then
                j -= 1
            Else
                Dim tmp As Char = chars(i)
                chars(i) = chars(j)
                chars(j) = tmp
                i += 1
                j -= 1
            End If
        End While

        Return New String(chars)
    End Function

    Sub Main()
        Dim s As String = "a1-bC2-dEf3-ghIj"

        Console.WriteLine(s)
        Console.WriteLine(reverseOnlyAlphabeticCharacters(s))
    End Sub

End Module


	
' run:
'
' a1-bC2-dEf3-ghIj
' j1-Ih2-gfE3-dCba
'

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...