VB .NET Chapter 8 String Manipulation

String Manipulation in VB .NET

Humans are far from perfect. Especially when they are entering data into textboxes! Sometimes they won't enter any details at all in the boxes you want them to. And then when they do enter something, they often get it wrong. Sometimes on purpose, just to trip you up. By manipulating Strings of data, we can check things like text in a textbox to see if it is correct, and thereby gain some control of the user's actions.
First, let's take a closer look at the String variable type.

The String Variable Type

There's more to the string variable type than meets the eye. You've used them a lot to store text. But the string variable types come with a lot of inbuilt power. Strings have their own properties and methods, just like a textbox or label or form does. That's because strings are objects. (In fact, all variables are objects in VB.NET, including the number variables.) In a later section, we'll be going into a bit more detail on objects. For now, think of them as things that can be manipulate - Like the textbox, label and form just mentioned.
And strings variables can be directly manipulated, too. An example should clear things up.
  • Start a new project.
  • Add two textboxes and a button to your new form.
  • For Textbox1, set the Text property to “string variables”.
  • Double click the button to open the coding window.
  • Type the following as the code for the button:
Dim strUpper As String
strUpper = TextBox1.Text
TextBox2.Text = strUpper.ToUpper( )

Run your code and see what happens when you click the button.
You should have found that the text from Textbox1 gets converted to uppercase letters.
The reason it gets converted is because we used the ToUpper method of the string variable. When you typed the full stop after the variable name, you probably saw this pop up box:
The intellisense list
Simply double click the method you want, and it's added to your code.
strUpper.ToUpper( )
Notice that the name of the variable you want to do something with comes first. Then, after the full stop, you add the name of the method.
It's easy to guess what some of the methods do (like ToLower), but others are a bit more enigmatic (Like Substring).
In this section, we'll go through some of the string methods to see what they do, and how useful they can be in your code.
Before we start, here's a full list of the methods that a string variable can access (it's a bit long, so it gets its own window!):
Common String methods in VB NET
Length on that list above is a property, and not method. We'll be using Length, as it comes in quite useful.

Manipulating data from a Text Box

You already know how to pass data from a Textbox into a variable. Just do this
Dim FirstName As String
FirstName = txtFirst.Text
Then whatever was in the Textbox you called txtFirst will get transferred directly to the String variable you set up. Once the data is in the variable, you can test it to see if it's the type of data you want. After all, the user could have entered numbers to try and trip you up. Or they could have left it blank.
  • Add a new textbox to your form
  • Change the Name property to txtFirst
  • Add a second button to your form
  • Set the Text property to whatever you want
  • Double click the button and add the following code:
Dim FirstName As String
FirstName = txtFirst.Text
If FirstName = "" Then
MsgBox "Please enter your First Name in the text box"
Exit Sub

End If
In this code, we are passing whatever is in the text box directly to the variable called FirstName. We are then testing what is inside the variable with an If statement. We want to test if the user has actually entered something into the text box. If they've left it blank, we want to tell them to try again. We also want to exit the Subroutine. After all, if they got it wrong, we don't want to proceed with any code we might have written.
The way we are testing to see if the user has left the text box blank is this:
If FirstName = "" Then
We've put two sets of double quotes together. This signifies a string of text that is blank. If the user didn't enter anything at all, then our variable FirstName will contain a blank string. This is what we're testing for.
Run the programme and try it out. Don't type anything at all in the textbox, but just click the button. The message box should display.
Now, click inside the textbox. Hit the space bar three times. And then click the button. Did the Message box display?
So why didn't it? After all, there was nothing in the textbox. Isn't that an blank string? What was passed to the variable?
Well, when you press the space bar Visual Basic counts that as a text character. So when you press the space bar three times what is in the variable is this:
FirstName = " "
and not this:
FirstName = ""
The two are entirely different, according to Visual Basic. After all, you might have wanted three spaces!
So how can we check to see if there is anything at all in our textbox? How do we defeat the user who has tried to fool us by hitting the space bar a number of times?
In the rest if this section, you'll learn about the various ways you can use the String methods and properties to examine what a particular string contains. First up is the Trim method.

The Trim Method in VB .NET

In the previous part you added code to transfer some text that was in a Textbox over to a variable. The code you wrote was this:
Dim FirstName As String
FirstName = txtFirst.Text
If FirstName = "" Then
MsgBox "Please enter your First Name in the text box"
Exit Sub

End If
But the user could press the spacebar in your textbox. Although there would be no letters or numbers inthe textbox, the above error checking wouldn't work - all of the blank spaces would get passed to your variable. We can use a String method called Trim to solve this problem.

The Trim Method

One of the methods on our list was Trim. What this does is to trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just "Text".
You use it in your code. Like this:
FirstName = txtFirst.Text
FirstName = FirstName.Trim

First, we put the text from the textbox into a variable called FirstName. Then we said "assign to the variable FirstName (FirstName = ) the value of FirstName trimmed (FirstName.Trim)".
Again, though, we're just adding the method we want after the variable name. VB will take care of the trimming for us.
Another way to Trim is to use the Trim() function directly. Like this:
FirstName = Trim( txtFirst.Text )
What you are trimming here is any blank spaces from around text entered directly in the text box called txtFirst
But we now have a way to thwart that user who is trying to trip us up by entering blank spaces into our text box. If you were programming a Form where the First Name was going into a database, then it's essential you trap anything like this.

OK, we've tested to see if the First Name text box was empty. Is there anything else we can do? What if our clever-clogs user tries to fool us again. This time he (they're always "he's"!) decides to enter some numbers. He claims his name is "George12345". Is there anything we can do to stop his little games? Is there a way to test that the data entered into a text box was text and not numbers?
Indeed there is! We'll use the Chars Property to see if we can check for numbers and text.

Char and Chars in VB .NET


Char ( NOT Chars)

Char is a variable type. It can hold one character at a time (the Char is short for Character). You set it up like this:
Dim OneCharacter As Char
You can then store a character in the variable like this:
OneCharacter = "A"
Or like this:
Dim OneCharacter As Char = "a"
You can even do this:
Dim OneCharacter As Char = "apple"
But if you try to put a whole word into a Char variable, only the first letter will be retained.
So what good is the Char variable type?
Well, a common use for it is to transfer one letter at a time from a string, and then test to see what this character is. You can test to see if it's a number, for example. Or perhaps to test if the string contains an "@" symbol for a valid email address. We'll test for a number. In the process, we can study the Length property of string variables.
Add another textbox and a button to your form from the first part of the tutorial. Change the Nameproperty of the textbox to txtChars. For the Text property of the Textbox, enter "George123". Double click the new button and enter the following variable declarations:
Dim OneCharacter As Char
Dim FirstName As String
Dim i As Integer
Dim TextLength As Integer

Remember what we're going to be doing here. We're going to put the text from the textbox into a string variable. Then we'll loop round every character in the string to see if it's a number.
So the next line to add to your code is the one that transfers the text from the textbox to the string variable. Add this:
FirstName = Trim(txtChars.Text)
The next thing we need is the length of the string. We need this for the end value of our loop. The length property will give us this answer. So add this line:
TextLength = FirstName.Length
The length property of a string variable tells you how many characters are in the string. You can add a message box to test out your code so far:
MsgBox("Number of characters is: " & TextLength)
Run your programme. Click the button and test out your code. You should see a message box popping up like this one:
A message box
So we've found out that "George123" has 9 characters.
We can now loop round each character in the string and test which ones are the numbers. Add the following For loop to your code (you can delete or comment out your message box line now):
For i = 0 To TextLength - 1
Next i
So the For loop starts at zero and ends at the length of the text, minus 1. (It will loop from 0 to 8 in our code - 9 characters. We'll see why you have to deduct 1 soon.
Inside of our loop, we need to grab one character at a time, and then put it into our Char variable. You can do that with the Chars() Property of the string variable type.


Chars (NOT Char)

Chars is a method of the String variable type. You can use it on any length of string, not just a Char variable. And that's the difference between the two: Char is a variable type, while Chars is a method you can use on Strings.
Chars works like this:
OneCharacter = FirstName.Chars(i)
You type the name of your variable, then after the full stop you add Chars(). Inside of the round brackets, you need a number. This number is the position in the string you want to grab. So if you wanted the third letter of a string variable, you'd put this:
Dim SomeString As String
Dim OneCharacter As Char

SomeString = "George123"
OneCharacter = SomeString.Chars(2)

The variable OneCharacter would then hold the third letter - "o".
The reason we've put 2 inside of the round brackets and not 3 is because VB starts counting the characters from zero, and NOT 1. And that's why our For Loop is this:
For i = 0 To TextLength - 1
You have to deduct 1 because the Chars() count starts at zero.
So amend your For Loop to this:
For i = 0 To TextLength - 1
OneCharacter = FirstName.Chars(i)
MsgBox(OneCharacter)

Next i
Run your code, and then click your button. You should get a message box displaying. In fact, you'll get 9 message boxes, one for each character in the string!
Ok, try these exercises to test your new knowledge.

Exercise K

Add an If statement to your For Loop. Check each character of the string "George123". If you find a number, display a suitable message, something like "A number was found". Exit the for loop when the first number is found.
To check if a variable is a number, you can use the IsNumeric( ) function. This function will return either True or False. In other words, if the variable being checked is a number, then IsNumeric( ) is True; if IsNumeric( ) is not a number then False gets returned.
If IsNumeric(OneCharacter) Then

Exercise L

Amend your code to keep a count of how many characters in the string are numbers. Display the count in a message box.


The InStr() Method in VB .NET


String Position

The InStr( ) method of string variables tells you what the position of one string is inside another. For example, if your string was "me@me.com" and you wanted to know if the string contained the@ symbol, you could use InStr( ) Method. You would use it like this
FirstString = "me@me.com"
SecondString = "@"

position = InStr( FirstString, SecondString )
The variable FirstString is the string we want to search; SecondString is what we want to search for. You can specify a starting position for the search to begin. If you do, this number goes at the start (the default is zero):
position = InStr( 1, FirstString, SecondString )
The variable called position has to be an integer variable. That's because the InStr() Method returns a number, and not text. In the code above, position would have a value of 3. That's because the @ symbols starts at the third letter of "me@me.com".
(Note: the InStr() Method starts counting at 1, and not zero like Chars(), which is very confusing!)
If the string you're searching for is not found, then the value placed inside of your integer variable (position in our case) is zero. That enables you to code something like this:
If position = 0 Then
MsgBox "Not a Valid email address: There was No @ Sign"
End If

The Substring() Method in VB .NET

Substring

Another useful string method is Substring. This allows you to grab one string within another. (For example, if you wanted to grab the ".com" from the email address "me@me.com")
In between the round brackets of Substring( ), you specify a starting position, and then how many characters you want to grab (the count starts at zero again). Like this:
Dim Email as String
Dim DotCom as String

Email = "me@me.com"
DotCom = Email.Substring( 5, 4 )

MsgBox(DotCom)
The message box would then display the characters grabbed from the string, in this case the ".com" at the end (start at position 5 in the string and grab 4 characters).
You could also do a check to see if an email address ended in ".com" like this:
Dim Email As String
Dim DotCom As String

Email = "me@me.con"
DotCom = Email.Substring( Email.Length - 4, 4 )

If DotCom = ".com" Then
MsgBox("Ends in Dot Com")
Else
MsgBox("Doesn't End in Dot Com")
End If
The starting position for Substring( ) this time is "Email.Length - 4". This is the length of the string variable called Email, minus 4 characters. The other 4 means "grab four characters"
You have to be careful, though. If there wasn't four characters to grab, VB would give you an error message.
We could replace the Chars() For loop code we wrote earlier with a Substring() method. The result would be the same. Here's the code:
For i = 0 To TextLength - 1
OneCharacter = FirstName.Substring( i, 1 )
MsgBox OneCharacter

Next i
So we're saying, "Start grabbing characters from the position i. Just grab one character".
Substring and Chars are very useful methods to use when you want to check the letters in a string of text.

Equals, Replace, and Insert Methods


The Equals Method

If DotCom = ".com" Then
MsgBox("Ends in Dot Com")
Else
MsgBox("Doesn't End in Dot Com")
End If
You can use the Equals method of string variables in the first line, instead of an equals ( = ) sign:
If DotCom.Equals( ".com" ) Then
So after the name of your string variable comes the full stop. Then select "Equals" from the popup list. In between the round brackets, you type the string (or variable name) that you want VB to compare.
The Equals method is used to compare one string of text against another. If they're the same a value of True is returned, else it's False.

The Replace Method

You can replace text in one string with some other text. The process is fairly straightforward. Here's some code that uses replace. Add a button to a form and test it out:
Dim OldText As String
Dim NewText As String

OldText = "This is some test"
NewText = OldText.Replace( "test", "text" )

MsgBox( OldText )
MsgBox( NewTex t)

When you run the programme, the first message box will say "This is some test" and the second box will say "This is some text".
The text you want to get rid of comes first. Then after a comma, type the new text. You can use string variables rather than direct text surrounded by double quotes, for example:
Dim NewWord As String = "Text"
NewText = OldText.Replace( "test", NewWord )


The Insert Method

You can also insert some new text into an string. Here's some code to try out:
Dim SomeText As String
Dim NewText As String

SomeText = "This some text"
NewText = SomeText.Insert( 5, "is " )

MsgBox( SomeText )
MsgBox( NewText )

The 5 in round brackets means start at position 5 in the string variable SomeText (the count starts at zero). You then type the text that you want inserted. You can use a variable name instead of direct text surrounded by quotes.

Split() and Join() in VB .NET

Two very useful string variable methods are Split and JoinSplit() allows you to split a line of text and put each element (word or phrase) into an array; Join() allows you to join elements of an array into one line of text. An example or two might clear this up.

The Split() Method

In a later project, you'll have to open up text file and read it's contents. You can read the text file line by line, and each line might be something like this:
"UserName1, Password1, UserName2, Password2, UserName3, Password3"
The programming problem is to separate each word. You can use Split for this. Each word would then be separated, ready for you to place into an array.
Here's an example for you to try out. (It's better to put this code behind a new button):
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String

LineOfText = "UserName1, Password1, UserName2, Password2"
aryTextFile = LineOfText.Split( "," )
For i = 0 To UBound(aryTextFile)
MsgBox( aryTextFile(i) )
Next i
Notice the line that sets up an array:
Dim aryTextFile() As String
We don't know how many elements will be in the array (how many words on each line), so we leave the round brackets blank.
The next line just put some text into a variable called LineOfText. But this can come from a text file that you open with code.
The line that does the splitting comes next:
aryTextFile = LineOfText.Split( "," )
Notice that aryTextFile has now lost its round brackets. If you put them in, you get an error. The use of the Split() method, though, is this:
LineOfText.Split( "," )
After the name of your variable and the full stop, select (or type) the word Split. In between round brackets you put what is know as the separator. This is the symbol or punctuation mark that you are using to separate each element of your line. In our case, we're using a comma to separate the words in the line. But you can use anything you like (a hyphen, for example).
When VB finishes the splitting, it fills up your array. Each element will occupy one slot in your array. So in our example, aryTextFile(0) will hold a value of UserName1aryTextFile(1) will hold a value of Password1, etc.
The For loop is there to show you how to loop round each element in your array, and displays the results in a message box:
For i = 0 To UBound( aryTextFile )
MsgBox( aryTextFile(i) )
Next i
The first line includes this:
UBound( aryTextFile )
UBound means Upper Boundary of an array. In between the round brackets of UBound() you type the name of your array. Notice, though that the round brackets of the array have gone missing again.
So if your array was this:
MyArray(9)
The Upper Boundary of the array would be 9. So the end of the For Loop would then be 9. You code like this when you don't know how many elements are in your array.
The message box just displays what is in each position of your array:
MsgBox( aryTextFile(i) )
The point is that all of the words from your line of text have been split and placed into an array. You now need to know how to put the text back together again.

The Join() Method

The Join method is used when you want to join the elements of an array back together again. Here's some code which does exactly that.
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile(3) As String

aryTextFile(0) = "UserName1"
aryTextFile(1) = "Password1"
aryTextFile(2) = "UserName2"
aryTextFile(3) = "Password2"

LineOfText = String.Join( "-", aryTextFile )
MsgBox( LineOfText )
The line that joins each element in the array is this:
LineOfText = String.Join( "-", aryTextFile )
(NOTE: If you have an older version of the VB NET software, use LineOfText.Join instead ofString.Join.)
In between the round brackets of Join(), you first type what you want to use as a separator. Here, we're using an hyphen as a separator. Next, you put the name of your array. Again the round brackets from the array have gone missing.
When the line executes, the variable LineOfText will hold the following:
"UserName1-Password1-UserName2-Password2"
Once you have the array elements joined together, you could then write the line back to your text file.
Split and Join can be very useful indeed. Especially when you're working with text files. Speaking of which, the next section deals with exactly this subject.


Comments