Code Snippet
Module stringFunctions
Public Function leftString(ByVal aString As String, ByVal numOfChars As Integer)
aString = aString.Substring(0, numOfChars)
Return aString
End Function
Public Function rightString(ByVal aString As String, ByVal numOfChars As Integer)
aString = aString.Substring(aString.Length - numOfChars)
Return aString
End Function
Public Function Mid(ByVal aString As String, ByVal startPosition As Integer, ByVal numOfChars As Integer)
aString = aString.Substring(startPosition - 1, numOfChars)
Return aString
End Function
Public Function Replace(ByVal aString As String, ByVal startPosition As Integer, ByVal newString As String)
Dim tempString As String = aString
aString = leftString(tempString, startPosition - 1)
aString &= newString
aString &= tempString.Substring(startPosition - 1 + newString.Length)
Return aString
End Function
End Module
Public Class Form1
'The next highlighted line should be one line of code in the code window.>>
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "The quick brown fox jumps over the lazy dog."
Dim
str2 As
String
= strDim
result As
String
result = leftString(str, 19)
MsgBox(result)
'or
MessageBox.Show(result)
'MessageBox has 21 overloads.
result = rightString(str, 4)
MessageBox.Show(result)
result = Mid(str, 5, 15)
MessageBox.Show(result)
result = Mid(str, 1, 30)
MessageBox.Show(result)
'Mid$ in some old version of BASIC could replace a word in a string.
'E.G. Mid$(str,41,3)="cat" would replace dog with cat.
'The string.Replace is okay for a single instance of a word.>>
str = str.Replace(
"dog"
, "cat"
)MessageBox.Show(str)
'It is NOT okay where two of the same word exist.>>
str = str.Replace(
"cat"
, "the"
)'Now we have two of the word "the"
'Watch this.>>
str = str.Replace(
"the"
, "very"
)MessageBox.Show(str)
'Reset original string "str" to the original string.
str = str2
MessageBox.Show(str)
'Same as Mid$(str,5,
5)="smart"
'The 2nd "
5" is not needed as the FUNCTION uses the String.Length
str = Replace(str, 5,
"smart"
)MessageBox.Show(str)
End
Sub
End Class