| << 4.3.4- Logical Operators | Chapter4 | 4.4.0- Conversions >> |
Concatenating Variables
It makes sense to add integers together, using expressions such as 2 + 3, or
Number1 + Number2 (as we showed above), but what happens if you wish to 'add' strings together? It doesn't make much sense to add them in the arithmetic sense – "Beans" plus "Rice" doesn't have a tangible meaning. However, VBScript allows us to 'add' strings together in a different sense – using a process known as concatenation.
When two strings are concatenated, the second string is attached at the end of the first string, creating a new string. In order to concatenate two strings we use the ampersand operator (&). Let's run through a few examples. We can concatenate the strings "Helter" and "Skelter", as follows:
strConcatenate = "Helter" & "Skelter"
Here, the result of the concatenation is the string "HelterSkelter", which will be assigned to the variable strConcatenate, of type string. You should note that VBScript won't automatically put in spaces or commas, though. You can also concatenate a number of strings within the same expression. Here, we'll concatenate three strings, one of which is a space (which is also a string since a space is a character):
strConcatenate = "Helter" & " " & "Skelter"
Now, strConcatenate will contain the string "Helter Skelter". You can concatenate as many string variables as you like (within the maximum length of 255 characters in VBScript):
strFirst = "Never "
strLearline = strFirst & strFirst & strFirst & strFirst & strFirst
Then strLearLine will contain the line "Never Never Never Never Never ".
Comparing Variables with a String SubType
Although you can't add or subtract strings numerically, this doesn't account for the comparison operators. These can be used to help compare and sort text into alphabetical order. So if you wished to find out which came first in the alphabet aardvark or anteater, the following code could be used:
strAnimal1 = "Aardvark"
strAnimal2 = "Anteater"
If strAnimal1 < strAnimal2 Then Response.Write "Aardvark"
If strAnimal2 < strAnimal1 Then Response.Write "Anteater"
It doesn't take a genius to figure out that the program will return Aardvark, however, if you were comparing the contents of variables, which depend on input from users, then this can alphabetically sort data for you without the need to refer to a database. We will look at sorting in databases in detail in chapters 12, 13, and 14.
| << 4.3.4- Logical Operators | Chapter4 | 4.4.0- Conversions >> |

RSS

