by Eric A. Johnson (4 Submissions)
Category: String Manipulation
Compatability: VB.NET
Difficulty: Unknown Difficulty
Originally Published: Sun 2nd April 2006
Date Added: Mon 8th February 2021
Rating: (1 Votes)
This function can be used to swap any two characters within a string. It returns the original string if the positions to swap are identical,
' original string; if out-of-bounds, returns empty string ("").
' NOTE: Positions start from 0; adjust calling values accordingly.
Private Function SwapCharsInString(ByVal originalString As String, _
ByVal position1 As Integer, ByVal position2 As Integer) As String
Dim tempString As String
Dim char1, char2 As Char
' If the positions to swap are identical, return original string
If position1 = position2 Then
Return originalString
End If
' If one of the positions to swap is past the boundary, return empty string
If (position1 >= originalString.Length) Or (position2 >= originalString.Length) Or _
(position1 < 0) Or (position2 < 0) Then
Return ""
End If
' The positions have passed all tests; we can swap positions now.
tempString = originalString
char1 = tempString.Chars(position1)
char2 = tempString.Chars(position2)
tempString = tempString.Remove(position1, 1)
tempString = tempString.Insert(position1, char2.ToString)
tempString = tempString.Remove(position2, 1)
tempString = tempString.Insert(position2, char1.ToString)
Return tempString
End Function
No comments have been posted about This function can be used to swap any two characters within a string. It returns the original strin. Why not be the first to post a comment about This function can be used to swap any two characters within a string. It returns the original strin.