Introduction to Programming Using Visual Basic 2005, An (6th Edition)
3.4. StringsThe most common types of data processed by Visual Basic are numbers and strings. Sentences, phrases, words, letters of the alphabet, names, telephone numbers, addresses, and Social Security numbers are all examples of strings. Formally, a string literal is a sequence of characters that is treated as a single item. String literals can be assigned to variables, displayed in text boxes and list boxes, and combined by an operation called concatenation (denoted by &). Variables and Strings
A string variable is a name used to refer to a string. The allowable names of string variables are the same as those of numeric variables. The value of a string variable is assigned or altered with assignment statements and displayed in a list box like the value of a numeric variable. String variables are declared with statements of the form Dim varName As String
Example 1.
If x, y, ..., z are characters and strVar is a string variable, then the statement strVar = "xy...z"
assigns the string literal xy...z to the variable and the statement lstBox.Items.Add("xy...z") or lstBox.Items.Add(strVar)
displays the string xy...z in a list box. If strVar2 is another string variable, then the statement strVar2 = strVar
assigns the value of the variable strVar to the variable strVar2. (The value of strVar will remain the same.) String literals used in assignment or lstBox.Items.Add statements must be surrounded by quotation marks, but string variables are never surrounded by quotation marks. Using Text Boxes for Input and Output
The content of a text box is always a string. Therefore, statements such as strVar = txtBox.Text
and txtBox.Text = strVar
can be used to assign the contents of the text box to the string variable strVar and vice versa. Numbers typed into text boxes are stored as strings. Such strings must be converted to Double or Integer numeric values before they can be assigned to numeric variables or used in numeric expressions. The functions CDbl and CInt convert strings representing numbers into numbers of type Double and Integer, respectively. Going in the other direction, the function CStr converts a number into a string representation of the number. Therefore, statements such as dblVar = CDbl(txtBox.Text)
and txtBox.Text = CStr(dblVar)
can be used to assign the contents of a text box to the Double variable numVar and vice versa. CDbl, CInt, and CStr, which stand for "convert to Double," "convert to Integer," and "convert to String," are referred to as data-conversion or type-casting functions. Example 2. |
The following program computes the sum of two numbers supplied by the user:
Private Sub btnCompute_Click() Handles btnCompute.Click Dim num1, num2, sum As Double num1 = CDbl(txtFirstNum.Text) num2 = CDbl(txtSecondNum.Text) sum = num1 + num2 txtSum.Text = CStr(sum) End Sub
[Run, type 45 into the first text box, type 55 into the second text box, and click on the button.] |
Concatenation
Two strings can be combined to form a new string consisting of the strings joined together. The joining operation is called concatenation and is represented by an ampersand (&). For instance, "good" & "bye" is "goodbye". A combination of strings and ampersands that can be evaluated to form a string is called a string expression. The assignment statement and the Add method evaluate expressions before assigning them or displaying them.
Example 3.
The following program illustrates concatenation. (The form for this example contains a button and a text box.) Notice the space at the end of the string assigned to quote1. If that space weren't present, then the statement that assigns a value to quote would have to be quote = quotel & " " & quote2. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim quote1, quote2, quote As String quote1 = "The ballgame isn't over, " quote2 = "until it's over." quote = quote1 & quote2 txtOutput.Text = quote & " Yogi Berra" End Sub
[Run, and then click the button. The following is displayed in the text box.] The ball game isn't over, until it's over. Yogi Berra
|
Visual Basic also allows strings to be concatenated with numbers and allows numbers to be concatenated with numbers. In each case, the result is a string.
Example 4. (This item is displayed on pages 91 - 92 in the print version)
The following program concatenates a string with a number. Notice that a space was inserted after the word "has" and before the word "keys." (The form for this example contains a button and a text box.) Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim str As String, numOfKeys As Double str = "The piano keyboard has " numOfKeys = 88 txtOutput.Text = str & numOfKeys & " keys." End Sub [Run, and then click the button. The following is displayed in the text box.] The piano keyboard has 88 keys. |
The statement
strVar = strVar & strVar2
will append the value of strVar2 to the end of the current value of strVar. The same result can be accomplished with the statement
strVar &= strVar2
String Properties and Methods: Length Property and ToUpper, ToLower, Trim, IndexOf, and Substring Methods
We have seen that controls, such as text and list boxes, have properties and methods. A control placed on a form is an example of an object. A string is also an object, and, like a control, has both properties and methods that are specified by following the string with a period and the name of the property or method. The Length property gives the number of characters in a string. The ToUpper and ToLower methods return an uppercase and lowercase version of the string. The Trim method returns the string with all leading and trailing spaces deleted. The Substring method returns a sequence of consecutive characters from the string. The IndexOf method searches for the first occurrence of one string in another and gives the position at which the string is found.
If str is a string, then
str.Length
is the number of characters in the string,
str.ToUpper
is the string with all its letters capitalized,
str.ToLower
is the string with all its letters in lowercase format, and
str.Trim
is the string with all spaces removed from the front and back of the string. For instance,
"Visual".Length is 6. "Visual".ToUpper is VISUAL. "123 Hike".Length is 8. "123 Hike".ToLower is 123 hike. "a" & " bcd ".Trim & "efg" is abcdefg.
In Visual Basic, the position of a character in a string is identified with one of the numbers 0, 1, 2, 3, ....A substring of a string is a sequence of consecutive characters from the string. For instance, consider the string "Just a moment". The substrings "Jus", "mom", and "nt" begin at positions 0, 7, and 11, respectively.
If str is a string, then
str.Substring(m, n)
is the substring of str consisting of n characters beginning with the character in position m of str. If the comma and the number n are omitted, then the substring starts at position m and continues until the end of str. The value of
str.IndexOf(str2)
is -1 if str2 is not a substring of str, and otherwise is the beginning position of the first occurrence of str2 in str. Some examples using these two methods are as follows:
"fanatic".Substring(0, 3) is "fan". "fanatic".IndexOf("ati") is 3. "fanatic".Substring(4, 2) is "ti". "fanatic".IndexOf("a") is 1. "fanatic".Substring(4) is "tic". "fanatic".IndexOf("nt") is -1.
The IndexOf method has a useful extension. The value of str.IndexOf(str2, n), where n is an integer, is the position of the first occurrence of str2 in str in position n or greater. For instance, the value of "Mississippi".IndexOf("ss", 3) is 5.
Like the numeric functions discussed before, string properties and methods also can be applied to variables and expressions.
Example 5. (This item is displayed on pages 93 - 94 in the print version)
The following program uses variables and expressions with the property and methods just discussed: Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim str1, str2 As String str1 = "Quick as " str2 = "a wink" With lstResults.Items .Clear() .Add(str1.Substring(0, 7)) .Add(str1.IndexOf("c")) .Add(str1.Substring(0, 3)) .Add((str1 & str2).Substring(6, 6)) .Add((str1 & str2).ToUpper) .Add(str1.Trim & str2) .Add("The average " & str2.Substring(str2.Length 4) & _ " lasts .1 second.") End With End Sub
[Run, and then click the button. The following is displayed in the list box.] Quick a 3 Qui as a w QUICK AS A WINK Quick asa wink The average wink lasts .1 second.
|
Note: In Example 5, c is in the third position of str1, and there are three characters of str1 to the left of c. In general, there are n characters to the left of the character in position n. This fact is used in Example 6.
Example 6.
The following program parses a name. The fifth line locates the position, call it n, of the space separating the two names. The first name will contain n characters, and the last name will consist of all characters to the right of the nth character. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Dim fullName, firstName, lastName As String Dim n As Integer fullName = txtName.Text n = fullName.IndexOf(" ") firstName = fullName.Substring(0, n) lastName = fullName.Substring(n + 1) With lstResults.Items .Clear() .Add("First name: " & firstName) .Add("Your last name has " & lastName.Length & " letters.") End With End Sub [Run, type "John Doe" into the text box, and then click the button.] |
The Empty String
The string "", which contains no characters, is called the empty string or the zero-length string. It is different from "", the string consisting of a single space.
The statement lstBox.Items.Add("") skips a line in the list box. The contents of a text box can be cleared with either the statement
txtBox.Clear()
or the statement
txtBox.Text = ""
Initial Value of a String
When a string variable is declared with a Dim statement, it has the keyword Nothing as its default value. To specify a different initial value, follow the declaration statement with an equal sign followed by the initial value. For instance, the statement
Dim today As String = "Monday"
declares the variable today to be of type String and assigns it the initial value "Monday."
An error occurs whenever an attempt is made to perform an operation on a variable having the value Nothing or to display it in a list box. Therefore, unless a string variable is guaranteed to be assigned a value before being used, you should initialize iteven if you just assign the empty string to it.
Option Strict
Visual Basic allows string variables to be assigned to numeric variables and vice versa. However, doing so is considered poor programming practice, and Visual Basic provides a device, called Option Strict, to prevent it. When the statement
Option Strict On
is placed at the very top of the Code window, Visual Basic requires the use of type-casting functions when assigning string values to numeric variables and assigning numeric values to string variables. In addition, Option Strict On requires type-casting functions when assigning a Double value to an Integer variable.
Visual Basic provides a way to enforce Option Strict for all programs. Press Alt/Tools/Options to open the Options dialog box. In the left pane, click on the + sign to the left of Projects and Solutions to expand this entry. Then click on the subentry VB Defaults. Three default project settings will appear on the right. Set the default for Object Strict to On and then click on the OK button. From now on, all new programs will enforce Object Strict.
When Option Strict is in effect, values of Integer variables can be assigned to Double variables, but not vice versa. Actually, great care must be taken when computing with Integer variables. For instance, the value of an expression involving division or exponentiation has type Double and therefore cannot be assigned to an Integer variable even if the value is a whole number. For instance, none of the four assignment statements that follow is acceptable with Option Strict in effect:
Dim m As Integer Dim n As Double m = n m = 2.5 m = 2 ^ 3 m = 6 / 2
Throughout this book, we assume that Option Strict is in effect. Therefore, in order to not have to worry about the four occurrences just discussed, we restrict the use of the Integer variables primarily to counting rather than computation.
Internal Documentation
Program documentation is the inclusion of comments that specify the intent of the program, the purpose of the variables, and the tasks performed by individual portions of the program. To create a comment statement, just begin the line with an apostrophe. Such a statement appears green on the screen and is completely ignored when the program is executed. Comment lines appear whenever the program is displayed or printed. Also, a line of code can be documented by adding an apostrophe, followed by the desired information, after the end of the line.
Example 7.
The following rewrite of Example 6 uses internal documentation. The first comment describes the entire program, the comment in line 4 gives the meaning of the variable, and the final comment describes the purpose of the With block. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Determine a person's first name and the length of the second name Dim fullName, firstName, lastName As String Dim n As Integer 'location of the space separating the two names fullName = txtName.Text n = fullName.IndexOf(" ") firstName = fullName.Substring(0, n) lastName = fullName.Substring(n + 1) 'Display the desired information in a list box With lstResults.Items .Clear() .Add("First name: " & firstName) .Add("Your last name has " & lastName.Length & "letters.") End With End Sub |
Some of the benefits of documentation are as follows:
Other people can easily understand the program.
You can understand the program when you read it later.
Long programs are easier to read because the purposes of individual pieces can be determined at a glance.
Even though Visual Basic code is easy to read, it is difficult to understand the programmer's intentions without supporting documentation. Good programming practice dictates that developers document their code at the same time that they are writing it. In fact, many software companies require a certain level of documentation before they release a version, and some judge their programmers' performances on how well their code is documented. A rule of thumb is that 10% of the effort developing a software program is the initial coding, while the remaining 90% is maintenance. Much of the anxiety surrounding the fixing of the "Year 2000" problem was due to the enormous amount of effort required by programmers to read and fix old, undocumented code. The challenge was compounded by the fact that most of the original programmers of the code were retired or could not recall how their code was written.
Line-Continuation Character
Thousands of characters can be typed in a line of code. If you use a statement with more characters than can fit in the window, Visual Basic scrolls the Code window toward the right as needed. However, most programmers prefer having lines that are no longer than the width of the Code window. A long statement can be split across two or more lines by ending each line (except the last) with the underscore character (_) preceded by a space. Make sure the underscore doesn't appear inside quotation marks, though. For instance, the line
msg = "640K ought to be enough for anybody. (Bill Gates, 1981)"
can be written as
msg = "640K ought to be enough for " & _ "anybody. (Bill Gates, 1981)"
The line-continuation character does not work with comment statements. That is, each line of a comment statement must be preceded by an apostrophe.
Comments
From the Code window, you can determine the type of a variable by letting the mouse cursor hover over the variable name until a tooltip appears.
Variable names should describe the role of the variable. Also, some programmers use a prefix, such as dbl or str, to identify the type of a variable. For example, they would use names like dblInterestRate and strFirstName. This device is not needed in Visual Basic for the reason mentioned in Comment 1.
The functions CInt and CDbl are user friendly. If the user types a number into a text box, but types in a comma as the thousands separator, the values of CInt(txtBox.Text) and CDbl(txtBox.Text) will be the number with the comma removed.
The Trim method is useful when reading data from a text box. Sometimes users type spaces at the end of the input. Unless the spaces are removed, they can cause havoc elsewhere in the program.
There are several alternatives to CStr for casting a value to a string value. For instance, the statement
strVar = CStr(dblVar)
can be replaced with any of the following statements:
strVar = CType(dblVar, String) strVar = convert.ToString(dblVar) strVar = dblVar.ToString
Colorization. You can specify colors for the different elements of a program. For instance, in this book keywords are colored blue, comment statements are colored green, and strings are colored maroon. To specify the color for an element, Click on Options in the Tools menu. Then click on the + sign to the left of Environment to expand this entry, and click on the subentry Fonts and Colors. At this point, you can select an item from the Display list and specify the items foreground and background colors.
Practice Problems 3.4
1. | What is the value of "Computer".IndexOf("E")? |
2. | What is the difference in the output produced by the following two statements? Why is CStr used in the first statement, but not in the second? txtBox.Text = CStr(8 + 8) txtBox.Text = 8 & 8 |
Exercises 3.4
In Exercises 1 through 28, determine the output displayed in the text box or list box by the lines of code.
1. | txtBox.Text = "Visual Basic" |
2. | lstBox.Items.Add("Hello") |
3. | Dim var As String var = "Ernie" lstBox.Items.Add(var) |
4. | Dim var As String var = "Bert" txtBox.Text = var |
5. | txtBox.Text = "f" & "lute" |
6. | lstBox.Items.Add("a" & "cute") |
7. | Dim var As Double var = 123 txtBox.Text = CStr(var) |
8. | Dim var As Double var = 3 txtBox.Text = CStr(var + 5) |
9. | txtBox.Text = "Your age is " & 21 & "." |
10. | txtBox.Text = "Fred has " & 2 & " children." |
11. | Dim r, b As String r = "A ROSE" b = " IS " txtBox.Text = r & b & r & b & r |
12. | Dim s As String, n As Integer s = "trombones" n = 76 txtBox.Text = n & " " & s |
13. | Dim num As Double txtBox.Text = "5" num = 0.5 + CDbl(txtBox.Text) txtBox.Text = CStr(num) |
14. | Dim num As Integer = 2 txtBox.Text = CStr(num) txtBox.Text = CStr(1 + CInt(txtBox.Text)) |
15. | txtBox.Text = "good" txtBox.Text &= "bye" |
16. | Dim var As String = "eight" var &= "h" txtBox.Text = var |
17. | Dim var As String = "WALLA" var &= var txtBox.Text = var |
18. | txtBox.Text = "mur" txtBox.Text &= txtBox.Text |
19. | With lstBox.Items .Add("aBc".ToUpper) .Add("Wallless".IndexOf("lll")) .Add("five".Length) .Add(" 55 ".Trim & " mph") .Add("UNDERSTUDY".Substring(5, 3)) End With |
20. | With lstBox.Items .Add("8 Ball".ToLower) .Add("colonel".IndexOf("k")) .Add("23.45".Length) .Add("revolutionary".Substring(1)) .Add("whippersnapper".IndexOf("pp", 5)) End With |
21. | Dim a As Integer = 4 Dim b As Integer = 2 Dim c As String = "Municipality" Dim d As String = "pal" With lstOutput.Items .Add(c.Length) .Add(c.ToUpper) .Add(c.Substring(a, b) & c.Substring(5 * b)) .Add(c.IndexOf(d)) End With |
22. | Dim m As Integer = 4 Dim n As Integer = 3 Dim s As String = "Microsoft" Dim t As String = "soft" With lstOutput.Items .Add(s.Length) .Add(s.ToLower) .Add(s.Substring(m, n - 1)) .Add(s.IndexOf(t)) End With |
23. | How many positions does a string of eight characters have? |
24. | What is the highest numbered position for a string of eight characters? |
25. | (True or False) If n is the length of str, then str.Substring(n - 1) is the string consisting of the last character of str. |
26. | (True or False) If n is the length of str, then str.Substring(n - 2) is the string consisting of the last two characters of str. |
In Exercises 27 through 32, identify any errors.
27. | Dim phoneNumber As Double phoneNumber = "234-5678" txtBox.Text = "My phone number is " & phoneNumber |
28. | Dim quote As String quote = I came to Casablanca for the waters. txtBox.Text = quote & ": " & "Bogart" |
29. | Dim end As String end = "happily ever after." txtBox.Text = "They lived " & end |
30. | Dim hiyo As String hiyo = "Silver" txtBox = "Hi-Yo " & hiYo |
31. | Dim num As Double = 1234 txtBox.Text = Str(num.IndexOf("2")) |
32. | Dim num As Integer = 45 txtBox.Text = Str(num.Length) |
In Exercises 33 through 34, write an event procedure starting with a Private Sub btnCompute_Click(...) Handles btnCompute.Click statement, ending with an End Sub statement, and having one line for each step. Display each result by assigning it to the txtOutput.Text property. Lines that display data should use the given variable names.
33. | The following steps give the name and birth year of a famous inventor:
|
34. | The following steps compute the price of ketchup:
|
35. | The following steps display a copyright statement:
|
36. | The following steps give advice:
|
In Exercises 37 through 40, the interface is specified. Write the code to carry out the stated task.
37. | If n is the number of seconds between lightning and thunder, the storm is n/5 miles away. Write a program that requests the number of seconds between lightning and thunder and reports the distance of the storm. A sample run is shown in Figure 3.17. Figure 3.17. Sample output of Exercise 37.
|
38. | The American College of Sports Medicine recommends that you maintain your training heart rate during an aerobic workout. Your training heart rate is computed as .7 * (220 - a) + .3 * r, where a is your age and r is your resting heart rate (your pulse when you first awaken). Write a program to request a person's age and resting heart rate and then calculate the training heart rate. (Determine your training heart rate.) A sample run is shown in Figure 3.18. Figure 3.18. Sample output of Exercise 38.
|
39. | The number of calories burned per hour by bicycling, jogging, and swimming are 200, 475, and 275, respectively. A person loses 1 pound of weight for each 3500 calories burned. Write a program that allows the user to input the number of hours spent at each activity and then calculates the number of pounds worked off. A sample run is shown in Figure 3.19. Figure 3.19. Sample output of Exercise 39.
|
40. | Write a program to request the name of a baseball team, the number of games won, and the number of games lost as input, and then display the name of the team and the percentage of games won. A sample run is shown in Figure 3.20. Figure 3.20. Sample output of Exercise 40.
|
In Exercises 41 through 46, write a program with a Windows-style interface to carry out the task. The program should use variables for each of the quantities and display the outcome in a text box with a label as in Example 6.
41. | Request a company's annual revenue and expenses as input, and display the company's net income (revenue minus expenses). (Test the program with the amounts $550,000 and $410,000.) |
42. | Request a company's earnings-per-share for the year and the price of one share of stock as input, and then display the company's price-to-earnings ratio (that is, price/earnings). (Test the program with the amounts $5.25 and $68.25.) |
43. | Calculate the amount of a waiter's tip, given the amount of the bill and the percentage tip as input. (Test the program with $20 and 15 percent.) |
44. | Calculate a baseball player's batting average, given his times at bat and number of hits as input. Note: Batting averages are displayed to three decimal places. |
45. | Write a program that contains a button and a read-only text box on the form, with the text box initially containing 0. Each time the button is pressed, the number in the text box should increase by 1. |
46. | Write a program that requests a (complete) phone number in a text box and then displays the area code in another text box when a button is pressed. |
47. | Write a program that requests a sentence, a word in the sentence, and another word and then displays the sentence with the first word replaced by the second. For example, if the user responds by typing "What you don't know won't hurt you." into the first text box and know and owe into the second and third text boxes, then the message "What you don't owe won't hurt you." is displayed. |
48. | Write a program that requests a letter, converts it to uppercase, and gives its first position in the sentence "THE QUICK BROWN FOX JUMPS OVER A LAZY DOG." For example, if the user responds by typing b into the text box, then the message "B first occurs in position 10." is displayed. |
49. | The formula |
50. | Write a program that requests a positive number containing a decimal point as input and then displays the number of digits to the left of the decimal point and the number of digits to the right of the decimal point. |
Solutions to Practice Problems 3.4
1. | -1.There is no uppercase letter E in the string "Computer". IndexOf distinguishes between uppercase and lowercase. |
2. | The first statement displays 16 in the text box, whereas the second statement displays 88. With Option Strict in effect, the first statement would not be valid if CStr were missing, since 8+8 is a number and txtBox.Text is a string. Visual Basic treats the second statement as if it were txtBox.Text = CStr(8) & CStr(8) |
Категории