String manipulation means writing code to process non-numeric variables. Examples of the string are names, addresses, gender, cities, book titles, alphanumeric characters (@,#,$,%,^,&,*, etc) and more. In Visual Basic 2013, a string is a single unit of data that made up of a series of characters.They include letters, digits, alphanumeric symbols and more. It is treated as the String data type and cannot be manipulated mathematically though it might consist of numbers.
12.1 String Manipulation Using + and & signs.
In Visual Basic 2013, strings can be manipulated using the & sign and the + sign, both perform the string concatenation. It means combining two or more smaller strings into larger strings. For example, we can join “Visual”,”Basic” and “2013″ into “Visual Basic 2013″ using “Visual”&”Basic” or “Visual “+”Basic”, as shown in the Examples below:
Example 12.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim
text1, text2, text3, text4 As String
text1 = “Visual”
text2 = “Basic”
text3=”2013″
text4 = text1 + text2+text3
MsgBox (text4)
End Sub
The line text4=text1+ text2 + text3 can be replaced by text4=text1 & text2 &text3 and produces the same output. However, if one of the variables is declared as numeric data type, you cannot use the + sign, you can only use the & sign.
The output is shown in Figure 12.1:
Example 12.2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim text1, text3 as string
Dim Text2 As Integer
text1 = “Visual”
text2=22
text3=text1+text2
MsgBox(text3)
End Sub
This code will produce an error because of data mismatch. The error message appears as follows:
However, using & instead of + will be all right.
Dim text1, text3 as string
Dim Text2 As Integer
text1 = “Visual”
text2=22
text3=text1 & text2
MsgBox(text3)