Zebra0.com

visual-basic strings

The String class includes many methods for handling the string. Look at the examples below:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  Dim Alphabet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  Me.Text = Alphabet.Length() '26
  Me.Text = Alphabet.ToLower 'abcdefghijklmnopqrstuvwxyz
  Me.Text = Alphabet.Substring(0, 3) 'ABC  start=0, length=3
  Me.Text = Alphabet.Substring(5, 2) 'FG  start=5, length=2
  Me.Text = Alphabet.Substring(20) 'UVWXYZ   start=20, everything from tht point
  Me.Text = Alphabet.IndexOf("D") '3  note: A is 0, B is 1, etc.
  Me.Text = Alphabet.IndexOf("XYZ") '23   XYZ is found begining in position 23
  Me.Text = Alphabet.IndexOf("AX") ' -1   AX is not found
  Me.Text = Alphabet.StartsWith("A") 'True
  Me.Text = Alphabet.StartsWith("ABC") 'True
  Me.Text = Alphabet.StartsWith("XYZ") 'False
  Me.Text = Alphabet.EndsWith("YZ") 'True
  Me.Text = Alphabet.Replace("ABC", "*") '*DEFGHIJKLMNOPQRSTUVWXYZ
  Me.Text = Alphabet.Remove(5, 15) 'ABCDEUVWXYZ
  Me.Text = Alphabet.Contains("DEF") 'True
        
  Dim Sentence As String = "A man and a woman manage the store."
  Me.Text = Sentence.IndexOf("man") '2
  Me.Text = Sentence.LastIndexOf("man") '18 (in management)
  Me.Text = Sentence.Replace("man", "person") 'A person and a woperson personage the store.
  Dim Words As String() 'an array to hold the words in the sentence
  Words = Sentence.Split(" ") 'the space is used to split sentence into an array
  Me.Text = Words(2) 'and
  Me.Text = Words(Words.Length - 1) 'store. (last word in sentence plus the dot)
End Sub 'Form1_Load

Like arrays, the index on Strings begins with 0. The length() of Alphabet is 26, there are 26 letters with A in position 0 and Z in position 25. We can combine these functions in various ways. For example,

Me.Text = Alphabet.Substring(0, 12).Contains("X") 'False
Experiment: Try various combinations of these string functions.

NEXT: Names: Using String Functions