Chapter Fourteen
String Functions
Keywords: LEN, LEFT$, RIGHT$, MID$
Did you have any luck with your alphabetizing program? If not, don't despair; we will go through the development of the program in this chapter. Along the way, we will show you another trick or two. Let's get right to it.
To start off, we want our program to clear any clutter off the screen:
CLS
We will then ask the user for the number of words they will want to sort:
PRINT"How many words to sort";
INPUT NUMBER
Wait a minute! Have we forgotten something? If we are going to store and sort some variables, won't we need to dimension a subscripted variable? Yes. Here is our first trick! We will only set aside as much variable space as we need! How do we do that? QBASIC allows us to use a variable as the limit indicator in a dimension statement. Here is how our DIM statement will look:
DIM WORD$(NUMBER)
Now we simply have to enter in all of our data. We will use a method similar to the test scores program in last chapter, that is, printing out the number of each word as it is entered. Here we go:
FOR N=1 TO NUMBER
PRINT "Enter Word #"N;
INPUT WORD$(N)
NEXT N
Now we have all of our words entered into the subscripted variable, and we are using memory in the most efficient way possible at the same time! Incidently, if you enter a number of words that exceeds the available memory of the computer, you will get an Out of Memory message. Use a smaller number of words! We are not trying to store the entire dictionary here! The actual number at which the error message occurs is determined by many factors, including how QBASIC was loaded, and any other programs that are taking up memory. It is not our intention to explain the memory management capabilities of QBASIC, so don't worry about it.
Back to our program. Now that we have the words in our array, we simply need to sort them. To do this, we will use the exact same algorithm that we have been using to sort numbers. This time, instead of comparing and swapping numbers, we will be comparing and swapping words. Here is our next piece of program code:
FOR OUTER =1 TO NUMBER-1
FOR INNER=OUTER+1 TO NUMBER
IF WORD$(INNER)