Wyo VB - Ch. 5 Notes
Objective #1: Manipulate strings.
- A string
is a sequence of characters (letters, digits, and symbols) that may or not
spell an English word. A string can be made up of digits. For example "1234"
is a string. Strings very often spell phrases that can contain a blank space,
such as "John Doe" (where there is a blank space between the 'n'
and the 'D'. Programmers use double quotes to delimit strings. The "
symbol is considered a string delimiter.
- When working with strings, you should realize that:
- any string has a certain length, which is the number of characters (including
blank spaces and symbols) that make it up.
- strings can be joined together. This is called concatenation.
- Strings can be searched for the occurrence of a specific character.
- Strings can be displayed on the screen.
- Strings can be read from an object (e.g. textbox, label) on a form.
Users can enter strings into textboxes and your program can read those
strings.
- You can assign a string to a String variable with an assignment statement
assuming that the variable was declared with the String data type. For example,
strName = "John Doe"
assigns the string literal, "John Doe", to the variable, Name.
String literals are specific string values that you surround with double
quotes. In the example above, it is technically proper to say that strName
is a string variable and that "John Doe" is a string
literal but both are often simply called strings.
- Concatenation
is the operation in which you join together two strings. You must use the
concatenation operator which is the ampersand symbol (&). Note
that Visual Basic also allows you to use the plus symbol (+) as the concatenation
operator in some situations but you should use & instead. Look closely
at the following example:
strNameA = "John"
strNameB = "John "
strLastName = "Doe"
strExample1 = strNameA & strLastName
strExample2 = strNameB & strLastName
strExample1 is currently equal to "JohnDoe" and strExample2 is
"John Doe" because of the included blank space in strNameB.
- The Len
function counts the number of characters in a string. If strWord = "Programming",
then Len(strWord) = 11 since there are 11 characters in strWord. If strWord2
= " Programming is fun", then Len(strWord2) is 19 because of the
three spaces that are included in the strWord2. That is, there is a leading
space before the 'P' and two spaces that separate the words. Spaces ARE considered
to be characters and, therefore, they are counted as part of the length of
a string.
- In the string literal " Basic" the space before the 'B' is called
a leading space. In the string
literal, "Programming ", the space AFTER the last 'g' is called
a trailing space.
- Older versions of BASIC required string variables to have a dollar symbol
($) at the end of a string variable's name. This is not required in Visual
Basic although you will see your instructor and your textbook refer to strings
this way since "old habits die hard." Do not mind this inconsistency
since Visual Basic does still allow the $ symbol to be used in this way even
though it is optional.
Objective #2: Use the string comparison operators (=, <,
and >) and the StrComp(str1, str2, n) function.
- Strings can be compared using the string comparison operators (=,
<, and >) which happen to be the same as the arithmetic comparison operators
that are used to compare mathematical and Boolean expressions in Visual Basic.
- Visual Basic compares strings alphabetically with the string comparison
operators. In order to compare strings, VB simply examines the ASCII values
of the corresponding characters of each string starting with the leftmost
characters. Whichever first letter of the two strings has the lower ASCII
value causes that string to be considered less than the other string. In comparing
"Apple" to "Banana", VB first compares the ASCII value
of the 'A' in "Apple" to the 'B' in "Banana. You will see an
ASCII chart by choosing Search from the Help menu in Visual Basic and looking
up "ASCII". The ASCII value of 'A' is 65 which is less than the
ASCII value of 'B' which is 66. Therefore, "Apple" is considered
to be less than "Banana." If the two strings have the same first
character, then Basic compares the second characters with each other.
Examples:
("A" < "B") simplifies
to the Boolean value True since the ASCII value of A is 65 and the ASCII
value of B is 66.
("D" < "d") simplifies
to the Boolean value True since the ASCII value of uppercase D is 68 and
the ASCII value of d is 100.
("Apple" < "Banana") simplifies
to the Boolean value True since the ASCII value of A is 65 and the ASCII
value of B is 66.
("ABC" = ("A" & "BC")) simplifies
to True since the "ABC" is equal to "ABC" after the
string concatenation.
("Apple" < "Aphrodite") simplifies
to False since the ASCII value of the second p in Apple is 112 and the ASCII
value of h is 104.
("Zeus" < "aphrodite") simplifies
to True since the ASCII value of uppercase Z is 90 and the ASCII value of
lowercase a is 97.
Another Example:
strMyName = "Minich"
strYourName = "Anderson"
If (strMyName < strYourName) Then
MsgBox "Ha Ha, I greater than you (alphabetically
at least)"
End If
- Besides using the string comparison operators (<, >, =), you can also
use the StrComp
function to compare two strings to see if one string is less than, equal to,
or greater than another string. The value returned by StrComp is either:
-1 (if the first parameter is less than the second)
0 (if the first two parameters are equal)
1 (if the second parameter is less than the first one)
The third parameter of the function is either a 1 or a 0, indicating whether
or not the string comparison is to be case-sensitive or not. A 0 is used to
indicate case-sensitivity and a 1 for case-insensitivity. If a third parameter
is not specified, then the comparison is case-sensitive by default (as if
a 0 was the third parameter.)
Examples:
StrComp("Art", "Bill") = -1 since
"Art" is less than "Bill"
StrComp("Bill", "Art") = 1 since
"Bill" is greater than "Art"
StrComp("Bill", "Art", 1) = 1 since
"Bill" is greater than "Art" (the third parameter
doesn't really affect this answer)
StrComp("Art", "apple", 0) = -1 since
"Art" is less than "apple" and the comparison is case-sensitive
StrComp("Art", "apple", 1) = 1 since
'r' is greater than 'p' and the comparison is case-insensitive
StrComp("F","f",1) = 0 since
"F" is equal to "f" when the comparison is case-insensitive
Objective #3: Use the UCase, LCase, and Trim functions
appropriately.
- The UCase function is used to change lowercase letters into uppercase
letters. The LCase function is used to change uppercase letters into
lowercase letters. These functions can be used to make a program case-insensitive.
This would allow the user to type text input without regard to the "uppercaseness"
or "lowercaseness" of what he/she is typing.
Examples:
(UCase("bill") = "BILL") is
True since every letter of the string is changed to uppercase
(UCase("APPLE") = "APPLE")
is True since "APPLE" is already uppercase
(LCase("APPLE") > "Programming")
is True since lowercase a is greater than uppercase p
- In general, you cannot assume that the user is going to enter data into
your program in a consistent (or even logical) manner. Therefore, one person
may enter his name as "John Doe" whereas another may enter it as
"bill doe" (forgetting to capitalize proper nouns). This seems to
occur more than ever since computer users are so sloppy typing email messages
in lowercase letters. A skillful programmer can avoid any complications from
bad user input by using the UCase and LCase functions correctly.
- Similarly, users may enter trailing or leading spaces by accident when inputting
data. For example, someone may enter his name as " John Doe" (notice
the leading space before the 'J') and not "John Doe". Therefore,
you should use the Trim
function to avoid any complications. The Trim function takes a string
as a parameter and returns the string with all of its leading and trailing
spaces removed if any exist. Note that if you were comparing two strings where
one had a leading space then that one would always appear less than the other
even if the first non-white space character was alphabetically less than its
counterpart. That is, " Zeus" < "Arthur" (notice the
leading blank space before the Z) since the ASCII value of the leading space
in " Zeus" is 32, which is less than the ASCII value of 'A', which
is 65.
Examples:
Trim(" Fred") = "Fred"
Trim(" Fred ")
= "Fred"
Trim("Fred") = "Fred"
Objective #4: Use the Left, Right, and
Mid string functions to return a selected portions of a string.
- The Left function returns a specific number of characters
from the left end of a string variable, a string literal, or a text box.
Examples:
Left("John", 2) returns "Jo"
' note that "John" is a string literal
Left(strName, 5) returns "Sally"
if the string variable strName = "Sally Fields"
Left(txtEntry.Text, 3) returns "113"
if the Text property of the textbox txtEntry is "113,456"
- The Right function returns a specific number of characters
from the right end of a string expression.
- Examples:
Right("John", 3) returns "ohn"
Right(strName, 5) returns "ields"
if the string variable strName = "Sally Fields"
Right(txtEntry, 3) returns "456"
if the Text property of the textbox, txtEntry is "113,456"
- The Mid function returns a substring that begins with a
particular character of the original string and ends with a specified spot.
A substring is a part of a larger string.
- The general form of the Mid function is Mid(String Expression, StartPosition,
NumberOfCharacters). The third argument NumberOfCharacters is optional.
If it is not specified then the whole substring formed by the characters
after the StartPosition is returned.
Examples:
Mid("John", 3, 2) returns the string
literal "hn"
Mid(strName, 6, 3) returns " Fi"
(a total of 3 characters with the first one being a space) if the string
variable strName = "Sally Fields"
Mid(txtEntry, 3) returns "3,456"
if the Text property of the textbox, txtEntry is "113,456"
Objective #5: Use For/Next loops.
- A For/Next loop (often just called a For loop) allows you
to repeat a section of code many times over and over again. A For/Next loop
is called a definite loop (or determinate loop) because the
programmer knows exactly how many times the code will be repeated. Each
pass of the loop is called an iteration. If you know exactly how many
iterations are necessary for a certain task, you should use a For/Next loop
rather than another kind of loop that you will study later called an indefinite
loop.
- Example:
For intCounter = 1 To 100
Beep
Next intCounter
This loop will iterate exactly 100 times. Each time the loop iterates the
computer will Beep because of the Beep command that is located inside of
the body of the loop. The variable intCounter is called the loop's
control variable. It begins with the value of 1. Each time the loop
iterates the intCounter increases by one. So intCounter will be equal to
2 the second time around the loop and so on. When intCounter is equal to
100 the loop will iterate one last time. In the example above, the initial
value of intCounter is 1. The limit value of intCounter is 100.
Notice that the body of the For/Next loop is indented. Also realize that
you can place as many statements in the body of the loop as you wish.
- The loop variable can change by amounts other than 1 on each iteration.
The amount that the loop variable changes is called the loop's step size.
The default step size for Visual Basic For/Next loops is 1. However, you can
type the keyword Step followed by any other value to change the step size.
Examples:
- For intCounter = 1 To 100 Step 12
Beep
Next intCounter
- For intCounter = 100 To 1 Step -1
Beep
Next intCounter
- For sngAmount = 0 To 1 Step 0.1
Beep
Next sngAmount
- For intCounter = 2 To 11 Step 2
Beep
Next intCounter
Determine how many times each of the above loops would iterate as well as
how many times the computer would beep. Also, determine the final value
of the loop variable in each example.
- If you use a step size of 1, do not include the "Step 1" part
of the For statement. You will lose points on programs that include this unnecessary
code. It is considered to be acceptable style to use loop variables that consist
of a name with one letter as in the following example. Programmers often use
the loop variables i and j as loop variables if the variable has no other
purpose in the program. It is not a violation of Mr. Minich's Coding Standards
to use the variable i or j as loop control variable in a For loop.
Objective #6: Use Do/While loops.
- A Do While loop (sometimes called a Do loop) should be used
instead of a For/Next loop when you do not know the exact number of iterations
that the loop must make. That is, if there is a situation in which some process
must occur over and over again within a loop but you do not know when exactly
it will end then you should use a Do While loop. For example, if you ask the
user to input his test scores but your program does not necessarily know how
many tests he has taken you could use a Do While loop and simply tell the
user to enter the number -99 to end his list of input values. Of course, we
know that -99 will not be confused with his actual exam scores since it is
impossible to earn a -99 on an exam. In this case, -99 is called the sentinel
value that warns the loop that the inputs have ended just like Paul Revere
was a sentinel that warned the Americans that the British were coming.
- A Do While loop is called an indefinite
loop (or indeterminate loop) because you never
know exactly how many times it will iterate. Remember that a For/Next loop
is a definite loop (or determinate loop) because a programmer can count how
many times it will iterate based on its initial value, limit value, and step
value.
- In a Do While loop, a control expression is typed after the keywords
Do While. Visual Basic evaluates the control expression to either True or
False. If the control expression is True then VB does iterate the loop. If
it is False, VB skips the loop or stops iterating it. I prefer that you use
parentheses around the control expression of a Do While loop for readability
and style however VB does not require the use of parentheses.
- Example:
intCounter = -1
intTotalPoints = 0
intExam = 0
Do While (intExam <> -99)
intTotalPoints
= intTotalPoints + intExam
intCounter = intCounter + 1
intExam = InputBox("Enter
your next exam score (-99 to quit):")
Loop
intExamAverage = intExamTotalPoints / intCounter
Note that in the example above the user is prompted by the InputBox to enter
-99 to quit. Notice the use of an accumulator statement (intTotalPoints
= intTotalPoints + intExam) as well as the use of a counter statement (intCounter
= intCounter + 1). The loop allows the user to enter all of his or her exam
scores. After the loop finishes iterating, the exam average is computed
and stored in intExamAverage. Can
you find the bug that would cause a potential run-time error in the example
above? Can you rewrite the code to fix this logical error?
- You can use an Exit Do statement to exit or "break out of"
a Do loop. You can also use an Exit For statement to break out of a
For/Next loop. However, it is not wise to use these Exit statements unless
there is no other practical way to make the loop end naturally under the control
of its control expression.
Example:
Do While (intSentinel <> -99)
intExam = InputBox("Enter your next exam score
(-99 to quit): ")
If (intExam = -99)
Exit Do
End If
intCounter = intCounter + 1
intTotalPoints = intTotalPoints + intExam
Loop
in this loop, the loop immediately stops iterating if the user enters an exam
score of -99 before the intCounter counter variable is incremented by one.
- Be careful not to create infinite loops that iterate forever. If
a Do loop's control expression never becomes False, the loop will never end
possibly causing the user to be forced to turn off the computer itself! If
a For loop is constructed like this:
For i = 1 To 10 Step -1
it may never finish iterating.
- A flag variable is often used
to store the value 1 (meaning True) or 0 (meaning False). The programmer uses
the flag variable as a way of controlling some process in an algorithm. Flag
variables are often used in loops to send a signal to the control expression.
For example, in the code segment below intGameIsOver is used as a flag variable.
It sends a signal to the control expression of the loop if the user has scored
enough points to end the game and exit the loop. intGameIsOver is initially
set to the value 0 which indicates False (the game is NOT over). You should
name flag variables appropriately. The variable should be named in a way that
it's name indicates a True condition. (For example, in the segment below,
you should not use a flag variable with the name, intGameIsNotOver, since
it would probably make the logic of the algorithm harder for most fellow programmers
to follow.)
intGameIsOver = 0
Do While (GameIsOver = 0)
' a bunch of
statements would be located here
intUserPointsScored
= intUserPointsScored + intLastRoundScore
If (UserPointsScored
> 1000) Then
intGameIsOver
= 1
End If
Loop
- You should always surround your loops with blank lines in your code. This
makes your program easier to read and debug. That is, above all Do and For
loops you should include a blank line and below all Loop and Next statements,
you should include a blank line. In fact, your instructor may deduct points
for the failure to do so even though Visual Basic does not require these blank
lines. Blank lines used to make code easier to read are called white
space. Tabs and blank spaces that are also used for
the same purpose of making white space.
Objective #7: Keep running totals and count sequences of statements.
- Programmers often use what is called a counter statement
to control operations within a computer program's algorithm. A sample counter
statement is,
intCounter = intCounter + 1
The assignment statement, the computer first adds 1 to the "old value"
of the variable, intCounter. Then, the computer assigns that new larger
value to the same variable, intCounter. This type of counter statement can
be very handy when allowing a program to run over and over again until the
variable gets to a certain size. For example, this could allow a computer
game of PacMan give the user three lives and when he has been eaten the
third time, the game knows to end.
- In a related way, a program can use an accumulator statement to keep
a running total within a computer program with a statement
like,
intSum = intSum + intValue
The assignment statement adds the variable, intValue, to the original value
of intSum and assigns the newer larger value (unless intValue is equal to
a negative number) to intSum. Unlike a counter statement, this does not
add the same increment to the variable each time it is executed. It is useful
therefore to keep a running total of things like points in a computer game
or a bank balance in a banking program.