Equals, Replace, and Insert Methods


The Equals Method

In code previously, we had this:

If DotCom = ".com" Then

MessageBox.Show("Ends in Dot Com")


MessageBox.Show("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" )

MessageBox.Show( OldText )
MessageBox.Show( 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 " )

MessageBox.Show( SomeText )
MessageBox.Show( 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.


In the next part, we'll take a look at how to use Split() and Join in VB .NET.

Buy our VB NET Book Here