Strings |
|
Introduction to Strings |
As seen in Lesson 3, a string is one or a combination of characters. To declare a variable for it, you can use either the String or the Object data types. To initialize the variable, put its value in double-quotes and assign it to the variable. Here are examples: |
Public Module Exercise Public Function Main() As Integer Dim FirstName As Object Dim LastName As String FirstName = "William" LastName = "Sansen" Return 0 End Function End Module |
If you want, you can make the computer produce a beeping a sound in response to something, anything. To support this, the Visual Basic language provides a function called Beep. Its syntax is: Public Sub Beep() Here is an example of calling it: Module Exercise Public Function Main() As Integer Beep() Return 0 End Function End Module If this function is called when a program is running, the computer emits a brief sound.
As seen in Lesson 2, string concatenation consists of adding one string to another. to support this operation, you can use either the + or the & operator. Here are examples: Public Module Exercise Public Function Main() As Integer Dim FirstName As Object Dim LastName As String Dim FullName As String FirstName = "William" LastName = "Sansen" FullName = LastName + ", " & FirstName MsgBox("Full Name: " & FullName) Return 0 End Function End Module This would produce: If you have many strings to add to a primary string, you can use either the += or the &= operator. Here is an example: Public Module Exercise Public Function Main() As Integer Dim FullName As String FullName = "Sansen" FullName += ", " FullName += "William" MsgBox("Full Name: " & FullName) Return 0 End Function End Module
In Lesson 3, we had a brief introduction to strings. We learned that a string was a combination of characters. From our knowledge of using the computer, we know that, to create a string, we can press the desired characters on the keyboard. An example of a string would be: "Production". To have a repeating character in a string, you can press its key as many times as you want. For example, in "cooperation", you would press o twice. To programmatically perform such an operation, that is, to duplicate a character in a string, you can call the StrDup() function. This function is provided in two versions whose syntaxes are: Public Shared Function StrDup( _ ByVal Number As Integer, _ ByVal Character As { Char | String } _ ) As String ' -or- Public Shared Function StrDup( _ ByVal Number As Integer, _ ByVal Character As Object _ ) As Object The second argument is the character that will be duplicated. The first argument specifies the number of times to duplicate it. Here is an example: Public Function Main() As Integer Dim Start As Char = "We need your c" Dim End$ = "peration to expedite this matter" Dim Result$ Result$ = Start & StrDup(2, "o") & End$ MsgBox(Result$) Return 0 End Function This would produce:
If you have such a string, you may be interested in the individual characters it contains. In Lesson 3, we also saw that, to convert an expression to a character, you can call the CChar() function. Its syntax is: Function CChar(ByVal Expression As Object) As Char This function takes a value as argument. The argument must be convertible to a character. If so, the function returns a character.
The characters used in the US English and the most common characters of Latin-based languages are created in a list or map of character codes. Each character is represented with a small number between 0 and 255. This means that each character must fit in a byte. To help you find the equivalent ASCII character of such a number, the Visual Basic language provides a function named Chr. Its syntax is: Public Function Chr(ByVal CharCode As Integer) As Char When calling this function, pass a small number as argument. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Character As Char Dim Number As Integer Number = 114 Character = Chr(Number) MsgBox("The ASCII character of " & Number & " is " & Character) Return 0 End Function End Module This would produce: Besides finding the ASCII equivalent of a number, the Chr() function can be used to apply some behavior in a program. For example, a combination of Chr(13) and Chr(10) would break a line in an expression, which is equivalent to the vbCrLf operator.
If you pass a number lower than 0 or higher than 255 to the Chr() function, you would receive an error. The reason you may pass a number higher than 255 is that you may want to get a character beyond those of US English, such as â. To support such numbers, the Visual Basic language provides another version of the function. Its syntax is: Public Function ChrW(ByVal CharCode As Integer) As Char The W here represents Wide Character. This makes it possible to store the character in the memory equivalent to the Short integer data type, which can hold numbers from -32768 to 32767. Normally, you should consider that the character should fit in a Char data type,, which should be a positive number between 0 and 65535. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Character As Char Dim Number As Short Number = 358 Character = ChrW(Number) MsgBox("The ASCII character of " & Number & " is " & Character) Return 0 End Function End Module This would produce:
One of the most fundamental characteristics of a string is the number of characters it contains. This number is referred to as the length of a string. To assist you with finding the length of a string, the Visual Basic language provides a function named Len. Its syntax is: Public Shared Function Len(ByVal Expression As String) As Integer This function expects a string as argument. If the function succeeds in counting the number of characters, which it usually does, it returns the an integer. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Item As String Dim Length As Integer Item = "Television" Length = Len(Item) MsgBox("The number of characters in """ & Item & """ is " & Length) Return 0 End Function End Module This would produce:
Like a normal value, a character or a string can be passed to a procedure. When creating the procedure, enter the argument and its name in the parentheses of the procedure. Then, in the body of the procedure, use the argument as you see fit. Here is an example: Public Module Exercise Private Sub Show(ByVal Gdr As Char) MsgBox(Gdr) End Sub End Module When calling the procedure, you can pass a value for the argument in double-quotes. Here is an example: Public Module Exercise Private Sub Show(ByVal Sex As Char) MsgBox(Sex) End Sub Public Function Main() As Integer Show("F") Return 0 End Function End Module In the same way, you can apply any of the features we studied for procedures, including passing as many arguments as you want or passing a mixture of characters, strings, and other types of arguments. You can also create a procedure that receives an optional argument.
To create a function that returns a character or a string, create the procedure using the Function keyword and, on the right side of the parentheses, include the Char or String data type preceded by the As keyword. Here is an example we saw in Lesson 5: Public Module Exercise Function GetFullName$() Dim FirstName$, LastName$ FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ") Return LastName & ", " & FirstName End Function End Module When calling the function, you can use it as a normal procedure or you can retrieve the value it returns and use it as you see fit. Here is an example: Public Module Exercise Function GetFullName$() Dim FirstName$, LastName$ FirstName = InputBox("Enter First Name: ") LastName = InputBox("Enter Last Name: ") GetFullName = LastName & ", " & FirstName End Function Private Sub Show(ByVal Name As String, ByVal Gdr As String) MsgBox("=-= Student Registration =-=" & vbCrLf & _ "Full Name: " & Name & vbCrLf & _ "Gender: " & vbTab & Gdr) End Sub Public Function Main() As Integer Dim FullName As String FullName = GetFullName() Show(FullName, "Unknown") Return 0 End Function End Module Here is an example of executing the program: In the same way, you can apply any of the features of procedures and functions we studied in Lessons 5 and 6.
As mentioned already, a string is a combination of symbols or characters. An example is "Television". Each character in a string has an indexed position from 1 to its last character:
To find out what character occupies a certain position inside of a string, you can call the GetChar() function. Its syntax is: Public Shared Function GetChar( _ ByVal str As String, _ ByVal Index As Integer _ ) As Char The first argument is the string that will be considered. If you pass this argument as an empty string or Nothing, you would receive an error. The second argument is the position to be consider inside the string. The value must be between 1 and the length of the string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Item As String Item = "Television" MsgBox("The character at position 5 is " & GetChar(Item, 5)) Return 0 End Function End Module This would produce:
If you have a character and want to find its equivalent character, you can call the Asc() function. Its syntax is: Public Overloads Function Asc(ByVal String As Char) As Integer This function takes a character as argument. If the function is successful, it returns the numeric equivalent. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Character As Char Dim Number As Integer Character = "W" Number = Asc(Character) MsgBox("The number of " & Character & " is " & Number) Return 0 End Function End Module This would produce:
In Lesson 3, we saw that, to convert an expression to a string, you can call the CStr() function. Its syntax is: Public Function CStr(ByVal Expression As Object) As String The argument can be almost any expression but the compiler has to be able to convert it to a string, which in most cases it can. If it is successful, the function returns a string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim DateHired As Date DateHired = #1/4/2005# MsgBox("Date Hired: " & CStr(DateHired)) Return 0 End Function End Module This would produce: The CStr() function is used to convert any type of value to a string. If the value to be converted is a number, you can use the Str() function. Its syntax is: Public Shared Function Str(ByVal Number As Object) As String This function expects a number as argument. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Number As Double Number = 1450.5 / 2 MsgBox("1450.50 / 2 = " & Str(Number)) Return 0 End Function End Module This would produce:
In Lesson 3, we saw that the Visual Basic language supports hexadecimal number and we saw how to initialize an integer variable with a hexadecimal number. Now, on the other hand, if you have a decimal number but need it in hexadecimal format, you can convert it. To support this operation, you can call the Hex() function. Its syntax is: Public Shared Function Hex( _ ByVal Number As { Byte | SByte | Short | UShort | Integer | UInteger | Long | ULong | Object } _ ) As String This function is used to convert either an integer-based or a decimal number to its hexadecimal equivalent. It returns the result as a string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Number As UInteger Number = 286345 MsgBox(CStr(Number) & " in hexadecimal format is " & Hex(Number)) Return 0 End Function End Module This would produce:
If you have a decimal number you want to convert to its octal format, you can call the Oct() function. Its syntax is: Public Shared Function Oct( _ ByVal Number As { Byte | SByte | Short | UShort | _ Integer | UInteger | Long | ULong | Object } _ ) As String This function takes an integer-based or a decimal number and converts its octal equivalent. It returns the result as a string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Number As Integer Number = 286345 MsgBox(CStr(Number) & " in octal format is " & Oct(Number)) Return 0 End Function End Module This would produce:
If you are presented with a string or an expression whose cases must be the same, you can convert all of its characters in either uppercase or lowercase. To convert a character, a string or an expression to uppercase, you can call the UCase() function. These functions take one argument as the string or expression to be considered. The syntaxes are: Public Shared Function UCase(ByVal Value As Char) As Char Public Shared Function UCase(ByVal Value As String) As String The first version receives a character as argument. If the character is already in uppercase, it would be returned the same. If the character is not a readable character, no conversion would happen and the function would return it. If the character is in lowercase, it would be converted to uppercase and the function would then return the uppercase equivalent. The second version considers the argument supplied as a string. Any letter that is in lowercase in the string would be converted to uppercase. Any letter that is in uppercase would be preserved and would not be changed. Any non-alphabetic character in the string would be kept "as is". Here is an example: Public Module Exercise Public Function Main() As Integer Dim ProgrammingEnvironment As String ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition" MsgBox(UCase(ProgrammingEnvironment)) Return 0 End Function End Module This would produce:
To convert a character or a string to lowercase, you can call the LCase() function. It is overloaded in two versions whose syntaxes are: Public Shared Function LCase(ByVal Value As Char) As Char Public Shared Function LCase(ByVal Value As String) As String The first version receives a character as argument. If the character is not a readable symbol, it would be kept "as is". If the character is in lowercase, it would not be converted. If the character is in uppercase, it would be converted to lowercase. The second version of the function receives a string as argument. Any letter in uppercase in the string would be converted to lowercase. Any letter that is in lowercase would not be changed. Any non-alphabetic character in the string would be kept "as is". Besides the UCase() and the LCase() functions, to convert the cases of characters in a string, the Visual Basic language provides the StrConv() function. Its syntax is: Public Shared Function StrConv( _ ByVal str As String, _ ByVal Conversion As Microsoft.VisualBasic.VbStrConv, _ Optional ByVal LocaleID As Integer, ) As String This function produces a string. The first argument of this function is the string whose characters would be converted. The second argument specifies what type of conversion will be performed. This argument is a member of the VbStrConv enumeration. From what we have learned so far, this argument can have one of the following values:
The last argument is optional. It allows you to specify that language whose rules would be used to direct the conversion. By default, the compiler refers to the language of the operation system. In most computers in the United States, this would be US English. If for some reason, you would like to apply different rules, specify its language as the third argument. |
A sub-string is a character or a group of characters or symbols that are part of an existing string. The Visual Basic language provides functions to create, manipulate or manage sub-strings. The primary rule to keep in mind is that a sub-string is part of, and depends on, a string. In other words, you cannot have a sub-string if you do not have a string in the first place.
If you have an existing string but want to create a new string using a number of characters from the left side characters of the string, you can use the Left() function. Its syntax is: Public Shared Function Left( ByVal str As String, ByVal Length As Integer) As String The function takes two arguments and both are required. The first argument is the existing string. The second argument is the number of characters counted from the left side of the string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim Process As String Process = "learning" MsgBox("To " & Left(Process, 5) & " is to gain understanding") Return 0 End Function End Module This would produce:
To create a new string using one or more characters from the right side of an existing string, call a function named Right. Its syntax is: Public Shared Function Right(ByVal str As String, ByVal Length As Integer) As String Both arguments are required. The first argument is the original string. The second argument is the number of characters counted from the right side of the string. Here is an example: Public Module Exercise Public Function Main() As Integer Dim ProgrammingEnvironment As String ProgrammingEnvironment = "Microsoft Visual Basic" MsgBox("Q" & Right(ProgrammingEnvironment, 5) & " in MS DOS 5.2") Return 0 End Function End Module This would produce:
You may want to create a string using some characters either from the left, from the right, or from somewhere inside an existing string. To assist you with this, the Visual Basic language provides a function named Mid. Its syntax is: Public Module Exercise Public Function Main() As Integer Dim ProgrammingEnvironment As String ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition" MsgBox("The " & Mid(ProgrammingEnvironment, 10, 13) & " language") Return 0 End Function End Module This would produce:
One of the most regular operations you will perform on a string consists of finding out whether it contains a certain character or a certain contiguous group of characters. To help you with this operation, the Visual Basic language provides the InStr() function. It is overloaded with two versions whose syntaxes are: Public Shared Function InStr(_ ByVal String1 As String, _ ByVal String2 As String, _ Optional ByVal Compare As CompareMethod _ ) As Integer ' -or- Public Shared Function InStr(_ ByVal Start As Integer, _ ByVal String1 As String, _ ByVal String2 As String, _ Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _ ) As Integer In the first version of the function, the String1 argument is the string on which the operation will be performed. The String2 argument is the character or the sub-string to look for. If String2 is found in String1 (as part of String1), the function return the position of the first character. Here is an example: Public Module Exercise Public Function Main() As Integer Dim ProgrammingEnvironment As String ProgrammingEnvironment = "Microsoft Visual Basic Express Edition" MsgBox("In " & ProgrammingEnvironment & ", ""Basic"" is found at position " & _ InStr(ProgrammingEnvironment, "Basic")) Return 0 End Function End Module This would produce: The first version of the function asks the interpreter to check String1 from the left looking for String2. If String1 contains more than one instance of String2, the function returns (only) the position of the first instance. Any other subsequent instance would be ignored. If you want to skip the first instance or want the interpreter to start checking from a position other than the left character, use the second version. In this case, the Start argument allows you to specify the starting position from where to start looking for String2 in String1. The InStr() function is used to start checking a string from the left side. If you want to start checking from the right side, call the InStrRev() function. Its syntax is: Public Function InStrRev( ByVal StringCheck As String, ByVal StringMatch As String, Optional ByVal Start As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary ) As Integer
After finding a character or a sub-string inside of a string, you can take action on it. One of the operations you can perform consists of replacing that character or that sub-string with another character or a sub-string. To do this, the Visual Basic language provides the Replace() function. Its syntax is: Public Function Replace( ByVal Expression As String, ByVal Find As String, ByVal Replacement As String, Optional ByVal Start As Integer = 1, Optional ByVal Count As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary ) As String The first argument is the string on which the operation will be performed. The second argument is the character or string to look for in the Expression. If that character or string is found, the third argument is the character or string to replace it with. Here is an example: Public Module Exercise Public Function Main() As Integer Dim ProgrammingEnvironment As String ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition" MsgBox(Replace(ProgrammingEnvironment, "Basic", "C++")) Return 0 End Function End Module This would produce:
Once a string has been initialized, one of the operations you can perform on it consists of reversing it. To do this, you can call the StrReverse() function. Its syntax is: Public Function StrReverse(ByVal Expression As String) As String This function takes as argument the string that needs to be reversed. After performing its operation, the function returns a new string made of characters in reverse order. Here is an example: Public Function Main() As Integer Dim StrValue As String Dim StrRev As String StrValue = "République d'Afrique du Sud" StrRev = StrReverse(strValue) MsgBox(StrValue & vbCrLf & StrRev) Return 0 End Function This would produce: Because the StrReverse() function returns a string, you can write it as StrReverse$. The simplest string is probably one that you declared and initialized. In some other cases, you may work with a string that you must first examine. For example, for some reason, a string may contain an empty space to its left or to its right. If you simply start performing a certain operation on it, the operation may fail. One of the first actions you can take on a string would consist of deleting the empty space(s), if any on its sides. To remove all empty spaces from the left side of a string, you can call the LTrim() function. Its syntax is: Public Shared Function LTrim(ByVal str As String) As String To remove all empty spaces from the right side of a string, you can call the RTrim() function. Its syntax is: Public Shared Function RTrim(ByVal str As String) As String To remove the empty spaces from both sides of a string, you can call the Trim() function. Its syntax is: Public Shared Function Trim(ByVal str As String) As String
If you want to create a string made of one or more empty spaces, you can call the Space() function. Its syntax is: Public Shared Function Space(ByVal Number As Integer) As String This function is the programmatic equivalent to pressing the Space bar when typing a string to insert an empty space between two characters. To compare two strings, you can call the StrCmp() function. Its syntax is: Public Shared Function StrComp( _ ByVal String1 As String, _ ByVal String2 As String, _ <Microsoft.VisualBasic.OptionCompareAttribute> _ Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _ ) As Integer The first and the second arguments to this function are strings and both are required. After the function has performed the comparison, it returns
The third argument allows you to specify the comparison in binary or text format. This argument can have one of the following values:
Here is an example: Private Sub cmdCreate_Click() Dim strValue1 As String Dim strValue2 As String Dim iComparisonValue strValue1 = "République d'Afrique du Sud" strValue2 = "Republic of South Africa" iComparisonValue = StrComp(strValue1, strValue2, vbTextCompare) MsgBox "Comparing """ & strValue1 & """ with """ & _ strValue2 & """ produces " & CStr(iComparisonValue) End Sub This would produce:
|
|
||
Home | Copyright © 2008-2016, FunctionX, Inc. | |
|