Visual Basic/Built In String Functions
Two strings are equal if and only if they have exactly the same contents, meaning that they are both the same length and each character has a one-to-one positional correspondence. However there is a statement that can be placed at the top of a module that affects string comparisons:
Option Compare Text
If you include this statement then string comparisons in that module will be case insensitive. This can be convenient but can also cause a certain amount of confusion.
Many other languages test strings only for identity; that is, they only test whether two strings occupy the same space in memory. This latter operation is possible in Visual Basic using the StrPtr function.
Option Explicit Dim strHello as String Dim strHello2 as String strHello = "hello" strHello2 = "hello" If StrComp(strHello, strHello2) = 0 Then Debug.Print "The strings are the same." End If
You can also test to see if one string is greater than or less than another using the same operators as used for numbers: <, >, <=, >=, <>.
To decide whether a string is less than another the two are compared character by character and as soon as a character from one string is found to have a lower ASCII code than the corresponding (same position) character in the other string then first is declared to be less than the second. The converse test also works.
Another way of testing strings for equality is the StrComp function. The StrComp function is more sophisticated; it uses the lexicographic ordering of the characters not their ASCII codes.
There are two operators that concatenate or join strings in Visual Basic: + and &. It is best to stick to & because + tries to convert its arguments to numbers first and this can give unexpected results:
a = "aaa" b = "bbb" c = a + b d = a & b Debug.Print c, d
But if one of the arguments is actually a number and the other just looks like a number to Visual Basic this is what happens when you use +:
a = 123 b = "456" c = a + b d = a & b Debug.Print c, d 579 123456
To find out if one string is a substring of another, use the InStr function as follows:
If InStr("Hello","He") > 0 Then MsgBox "The second string is contained in the first string." End If If InStr("He","Hello") > 0 Then MsgBox "This never gets printed; wrong argument order." End If
InStr function returns the position of the substring if it is found or zero otherwise.
The two-argument use of InStr function is case-sensitive. A case-insensitive containment test can be done as follows:
If InStr(UCase("Hello"), UCase("he")) > 0 Then MsgBox "The second string is contained in the first string when we " & _ "disregard the case." End If
To replace a string with another string inside a third string, use the built-in function Replace as follows:
Result = Replace("Teh Beatles", "Teh", "The") 'results into "The Beatles"
Indexing and Substrings
Strings can be used almost as if they were lists of characters. The nth character in a string can be returned by subscripting:
Mid$(s, n, 1)
Note: the values of n start from 1, not 0
It is also possible to return a substring of a string. The same function is used but instead of specifying 1 you specify the length of the substring:
s = "abcdef" sublen = 3 Debug.Print Mid$(s, 2, sublen) bcd
If you ask for more characters than are available then you get just what there is, no error is raised:
s = "abcdef" sublen = 33 Debug.Print Mid$(s, 2, sublen) bcdef
You can also use Mid$ on the left hand side of an assignment:
Dim s As String s = "abcdef" Debug.Print s Mid$(s, 2, 3) = "xxx" Debug.Print s Mid$(s, 3, 1) = "abcdefgh" Debug.Print s Mid$(s, 2, 3) = "y" Debug.Print s abcdef axxxef axaxef ayaxef
Notice that when Mid$ is on the left it doesn't change the total length of the string it just replaces the specified number of characters. If the right hand side specifies fewer characters than are asked for, then only that number of characters is replaced; if it specifies more, only the number asked for is used.
String constants can be declared like any other constant:
Const s As String = "abcdef"
Strings are not objects so they do not have methods but there is a number of functions that manipulate strings. Note that none of the functions modify the original string, except for Mid$ when it is on the left hand side of an assignment statement:
- Returns the integer code of the first character of the string. The inverse function would be Chr.
- Returns the length of the string.
- Returns the character index of the first occurrence of the substring in a string or zero if the substring is not found.
- Like InStr except that it returns the byte position. It has to be remembered, that Visual Basic 6 strings are Unicode strings.
- Like InStr except that it returns the character position of the last occurrence of the substring.
- Returns the specified number of characters from the beginning of the string. If there are fewer characters in the string Left$ returns the whole string, no error is raised,
- Returns a number of characters starting at the given position, on the left hand side it replaces those characters,
- Returns the specified number of characters from the end of the string, if there are not that many characters, then Right$ returns the whole string.
- Returns true if the string looks like a number.
- LTrim$, RTrim$, Trim$
- Returns a copy of the string with leading, trailing or leading and trailing spaces removed respectively. Note that only ASCII spaces (character code 32) are removed, other whitespace characters such as tabs are treated as non-spaces.
- LCase$, UCase
- Converts the whole string to lower case or upper case respectively.
- Returns a number corresponding to the number found at the start of the string. Note that Val is not locale aware, which means that it always expects decimal points regardless of the regional settings of your computer; if you are reading from a comma delimited file this is probably the function you want to use.
- Returns a string corresponding to the given number. Like Val this is not locale aware. This is the function you should use if you are creating a text file containing numbers to be read on someone else's computer.
- Converts the expression to a string. This procedure is locale aware and the correct function to use if converting numbers and differently typed values to strings for user-display. Usually it is unnecessary because Visual Basic automatically converts when necessary and uses Regional Settings to do so.
- Converts a number to a string using a specific format. The format is provided as a string of characters, that shows how many digits should be given before and after the decimal point. Like CStr, Format$ is locale aware so the decimal separator will be whatever is specified in the user's Regional Settings. Format$ also provides for conversion of dates to various built-in and custom string formats.
- CBool, CByte, CCur, CInt, CLng, CSng, CDbl, CDec
- Locale aware conversions to Boolean, Byte, Currency, Integer, Long, Single, Double, Decimal.
- Chops a string into pieces and returns a Variant Array. If no delimiter is specified then spaces will be used. Delimiters may be any string of any length. Two adjacent delimiters delimit an empty string.
- Returns a string of Hex characters representing a number.
- Returns a string of Octal characters representing a number.
- Returns a string with occurrences of a specified substring replaced with a new string. Note that the substring and the new string do not have to be the same size.
- Returns -1 if the first string is less than the second, 0 if they are identical, +1 if the first is greater than the second. Takes an optional argument that determines the comparison algorithm: vbBinary for exact comparisons using the character codes, vbTextCompare for case insensitive comparisons.
Quotes in strings
Because the double quote (") is used to delimit strings, you can't use it directly to specify a quote within a string. For example
' Does not work - syntax error Debug.Print "Fred says "Hi" to you"
One way is to use that Chr() function to specify the character code (34)
' Works fine Debug.Print "Fred says " & Chr$(34) & "Hi" & Chr$(34) & " to you"
Another is to double the double-quotes. You might find this more or less readable than the above way.
' Works fine too Debug.Print "Fred says ""Hi"" to you"
|Previous: Strings||Contents||Next: Regular Expressions|