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 shifts a substring within a string. It takes as input the string, the starting position of the substring, the length of the
' left or right of its starting position. Parameters are:
' OriginalString : The string submitted to the function.
' PositionToShift: The starting position of the first character.
' NumChars : The number of characters to shift. If 0 or less, or the
' number of chars in the original string or more, it
' returns the original string.
' PlacesToShift : How many places to the left or right to shift the
' substring. If this would place any portion of it out
' of bounds, it returns an empty string. Negative numbers
' shift to the left, positive to the right; 0 returns the
' original string.
' Example : dim CoolString as String
' CoolString = ShiftString("Eric loves Jenny", 11, 5, -11)
' ' CoolString is now "JennyEric loves "
' CoolString = ShiftString(CoolString, 5, 4, 7)
' ' CoolString is now "Jenny loves Eric"
'
' A more complicated example would involve a nested use:
'
' dim Coolstring as String
' CoolString = ShiftString(ShiftString("Eric loves Jenny", _
' 11, 5, -11), 5, 4, 7)
' ' CoolString is now "Jenny loves Eric"
Private Function ShiftString(ByVal OriginalString As String, _
ByVal PositionToShift As Integer, _
ByVal NumChars As Integer, _
ByVal PlacesToShift As Integer) As String
' Variable declaration
Dim ShiftedString, SubString As String
Dim stringLength As Integer
ShiftedString = OriginalString
stringLength = ShiftedString.Length
' Error-checking section
If (NumChars < 0) Or (NumChars >= stringLength) Then
Return ShiftedString
End If
If PlacesToShift = 0 Then
Return ShiftedString
End If
If PositionToShift < 0 Or PositionToShift >= stringLength Then
Return ShiftedString
End If
If (PositionToShift + NumChars + PlacesToShift >= stringLength) Or _
(PositionToShift + PlacesToShift < 0) Then
Return ""
End If
' Get substring to shift
SubString = ShiftedString.Substring(PositionToShift, NumChars)
' Remove substring from original string
ShiftedString = ShiftedString.Remove(PositionToShift, NumChars)
' Insert substring into new position
ShiftedString = ShiftedString.Insert(PositionToShift + PlacesToShift, _
SubString)
Return ShiftedString
End Function
No comments have been posted about This function shifts a substring within a string. It takes as input the string, the starting positi. Why not be the first to post a comment about This function shifts a substring within a string. It takes as input the string, the starting positi.