Some String manipulation functions with example
- Getting the length of a string or variable
Dim StrText As String Dim r As Integer StrText = "How long is this text?" r = StrText.Length MsgBox(r) - Getting the substring from a string or variable
Dim r As String = "Welcome to the world" r = r.Substring(8) MsgBox(r) Dim r As String = "Welcome to the world" r = r.SubString(8, 6) MsgBox(r) - If you wish to search the text for a particular word, then you will use the IndexOf(Find word, StartPosition) function.
Dim r As String = "The weather is warm and sunny"
r = r.IndexOf("warm")
MsgBox(r)
This code starts at the beginning of 'The weather today is reasonably warm and sunny', because we didn't give a start position, and searches for the word 'warm' in it. If it does not find the word warm in the string, then it will return the value as 0, and you get a message saying '0'. However, if it finds the word, then it returns a number saying where it found the start of the word. In this case, you would see a message box saying '16' because the 'w' of warm is 16 characters into the string.
- Find and replace in a string
.Replace(search for text, replace with text) is used to search through a string, and replace certain words or characters with other ones. The Replace function returns the text that it has replaced.
Dim i As String = "Only a fool goes outside in the rain" i = i.Replace("fool", "brave bloke") MsgBox(i)
No comments:
Post a Comment