Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 35 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
35
Dung lượng
399,46 KB
Nội dung
If we want to add an intervening space, we need to explicitly add it, as in this example: greeting = myWord + " " + name; The addition (+) operator has been programmed to add two strings as well as two numbers. We say that this operator has been overloaded to do this additional operation. That means the language has two built-in functions for the addition sign—one that works for numbers being added and another that works for strings or characters being added. When the types of the arguments on either side of the + sign are read, the appropriate function for the + sign is executed. As you advance in your programming skills, you can learn how to write your own overloaded operators. Remember that the computer will know which function to use—it will use the one that corresponds to the data types that match it. See Figure 11.2. The workload that the plus sign normally has is to add two numbers. To overload it is to add another job to its workload—that of concatenation. The String as an Array 191 Figure 11.1 Each of the strings is viewed as an array, and the array greeting is seen as a composite of the other two strings. Here is another example of concatenation: String sentence = " My" + " name" + " is" + " John."; Notice that I added a space before each word so that the string will look good when it is printed. cout << sentence << endl; My name is John. String Functions In this section, we will use some of the typical string functions in C++: length, substring, and find. length is a useful function because it tells you how long your string is. Of course, you could just count the letters in the word, assuming it is not user input, and you would have the answer. But strings behave a little differently than the array. There is often a special character called a null character, which is put on the end of the string. I think of it as a stop sign, keeping the programmer from looking for any other letters in the string. Consider Figure 11.3 where one part shows an array loaded with characters, and the other shows a string with the same characters but also with the appended null character. 192 Chapter 11 n All About Strings Figure 11.2 A plus sign is shown with arguments on either side of it. Depending on the arguments present, the appropriate function will be used. Length and Substring Most languages have some kind of length function that returns the number of letters, including any other characters, like blanks, punctuation, and so on. Since you learned about functions in Chapter 8, we can practice calling that function. Except for some early languages, like Pascal, strings are treated as objects in C++ and Java. Although you will read about objects in Chapter 15, we will have to make some minor adjustments in the way we call functions. With regular functions, you make a call by matching the parameter list with the appropriate types in your call. Consider the following example. The heading of a length function could be as follows: int length ( String m ); String Functions 193 Figure 11.3 Both strings appear as array s, but the string on the right shows the terminating null character. So in ord er to call the length function, we would need to send in the appropriate parameter—a string argument. Here would be the call to the function: int m = length ( greeting); Notice that greeting was passed into the function so that length could work on it to find the length. Objects use a different way of calling a function, and this is how it would look: String greeting = "Hello James." ; cout << greeting.length( ); /* notice that greeting (the object) is followed by the function name, rather than being contained in the parentheses. That is the main difference in the call.*/ So let’s practice calling the length function again. String firstString = "My cat is " ; String secondString = "really cool."; String thirdString = firstString + secondString; cout << firstString.length( )<< " " << secondString.length( )<< endl; cout << thirdString.length(); // 10 followed by 12 then 22 (on the next line) are printed. // remember to count the blanks and punctuation. Once you know the function heading and more about object syntax, you can easily call other string functions that the language has. However, we will delay calls made by objects until we learn more about objects. So all of the functions that follow have different headings from the exact ones you find for the String object. However, the most important thing for you to understand is what each function does. Following is an example of a string function that can be useful: substring.A substring function will return a section of the string depending on what para- meters are provided. Taking a subsection of a string is called extracting from the string. Here are some typical substring headings: Note This code is for illustrative purposes so that you will know about the kinds of string functions you can call. However, you have not learned all of the grammar of C++, so I am presenting them in this way so that you can understand string functions even though we are not ready to look at the actual code in C++. 194 Chapter 11 n All About Strings // Warning: not Standard C++ code! String substring ( String m, int start ); String substring (String m, int start, int length); String substring ( String m, int start, int firstIgnored ); Notice that both functions have the same name, but their parameters differ. This is another example of overloading, specifically, function overloading. Here we are overloading a given function rather than the arithmetic operator. There are a couple of ways the extraction works. The first way is to take the string and find the first position where you want to start your new string, and then you extract everything both including and after that position. This is pretty easy to do. Let’s put objects aside for the moment and look at the following example where we call the first function: // Warning: not Standard C++ code! String m = "headhunter"; String result = substring (m, 4); /* result will contain "hunter" since the ’h’ of "hunter" is in the 4th slot of the array.*/ // Recall that all arrays in C++ begin with slot 0. String word = substring (m, 6); // word will contain "ter" since t is in slot 6 In the second example, there are two parameters besides the string m: the start and the length. This function behaves a little differently from the previous substring function. The start position still refers to the place where the extraction should begin, but length tells how long that new string should be from the starting place. Here are a couple of examples to demonstrate how this substring function works. // Warning: not Standard C++ code! String m = "headhunter"; String result = substring ( m, 4, 4); // result will contain "hunt" since the starting position is 4 followed by // the length of 4, meaning 4 characters are stored in the new string. In another example, let’s extract the first part of headhunter, namely, the string head. This is how we would do that: // Warning: not standard C++ code! String m = "headhunter"; String result = substring ( m,0,4); String Functions 195 // since 0 is the starting position, we extract the h at the beginning and // show 4 characters. You can even extract a string of one character. Look at this example: // Warning: not standard C++ code! String m = "headhunter"; String result = substring ( m,3,1); /* since the 3rd slot is the letter d followed by a length of 1, we extract only the letter d */ The third function has two parameters in addition to the string. The third parameter, instead of indicating the length of the newly extracted string, indicates the first slot that will not be part of the extraction. That’s a mouthful! Let’s look at an example to clarify how this works: // Warning: not standard C++ code! String m = "headhunter"; String result = substring ( m,4,8); /* since 4 is the starting position, we extract from slot 4 through slot 7 because 8 is the first slot we wish to exclude. Result will contain "hunt" */ Here’s another extraction using this same substring function: // Warning: not standard C++ code! String m = "headhunter"; String result = substring ( m,2,9); /* since 2 is the starting position, we extract from slot 2 through slot 8 because 9 is the first slot we wish to exclude. Result will contain "adhunte" */ Strings are objects in C++, so it is easier to wait until you learn something about objects to address how the syntax changes. Find and CharAt Just like the previous functions, we can’t really use the precise C++ code to call them, but at least we can look at what each of these functions does. The find function will take a string, call it firstString, and look for the occurrence of another string, called otherString, within it. If it finds otherString within the firstString string, it will return the slot (the index) where that string begins. If it does not find the string, it will return –1. 196 Chapter 11 n All About Strings Look at this typical find function heading: // Warning: not Standard C++ code int find ( String firstString, String otherString); Let’s look at an example to see how it works. // Warning: not standard C++ code! String firstString = "foolhardy"; String otherString = "hard"; int x = find(firstString, otherString); cout << x << endl; /* 4 will be printed on the screen. */ In another example, let’s pass in a string that is not in firstString. // Warning: not standard C++ code! String firstString = "foolhardy"; String otherString = "day"; int x = find(firstString, otherString); cout << x << endl; /* -1 will be printed on the screen. */ Obviously, "day" is not contained in the word "foolhardy", so the negative 1 passed into the x is clearly not an index value, since those values begin at zero. Note Negative 1 is a typical value used to indicate that something unusual has happe ned to an array, and likewise, a string. Arrays usually start with the 0 index and continue through the positive numbers. The negative 1 as a return value is a clever way of signaling that a problem has occurred. String functions are very precise. Words like day and Day will not be considered the same because of the difference in the d’s. Nor will day be found within Da y. charAt is a simple function that allows you to extract a character from a string. It behaves like the substring function where the length is always 1. Let’s look at an example: // Warning: not standard C++ code! String m = "foolhardy"; char letter = charAt(m,6); cout << letter << endl; /* r will be printed on the screen. */ String Functions 197 charAt is easier to use than the substring function we used previously. Even easier to use is the following overloaded operator: the brace set. The Brace Set Operator The last function we will examine is the brace set, which works directly on a string. The brace set represents another overloaded operator. We have seen the brace set before in accessing array elements— list[5], for example. By over- loading this operator, we are making the string as accessible as the arrays we studied. Look at how simple it is to use: // Warning: not standard C++ code! String m = "foolhardy"; cout << m[5] << endl; /* The letter a will be printed on the screen. */ Here’s a better example of the braces at work: // Warning: not standard C++ code! String m = "foolhardy"; String otherString = "hard"; for( x = 0; x < m.length( ); x++) cout << m[x] << endl; /* Each letter is printed on a separate line. */ Of course, it is easier to just print out a string all at once. But the brace operator allows you to treat the string like the array type. Summary The string is like an array of characters. In any language, there are str ing func- tions available to you. In C++ and Java, the string is an object, so objects call functions differently from the way we have studied function calls. We exam ined typical string functions like length, substring, find, charAt and two overloaded operators: + and [ ]. The + allows two strings to be combined or concatenated. The substring function extracts a string from another string. length will find the length of the string—this is the number of characters in the string, including any blanks or punctuation. find allows you to find the first occurrence of one string within another. If the string is not found, a value like –1 will be returned. charAt extracts a single character from a string. Finally, the brace set allows the string to be manipulated in the same way as an array. 198 Chapter 11 n All About Strings The Matrix—Before the Movie In this chapter, we will examine the matrix, which is an interesting data structure. It is a two-dimensional holder for variables and is best understood as a grid or table. You will learn how to assign values to each spot in the matrix as well as learn how to retrieve values already stored in it. The last thing we will examine is the diagonal—an important part of the matrix. In This Chapte r n The grid of rows and columns n Loading one row at a time n Nested for loops n Manipulating a matrix n The diagonal of a matrix The Matrix as a Grid Now that we have studied the array, it would be good to examine the matrix, which is the name given to any multi-dimensional array. You might recall from an algebra II class the word ‘‘matrix.’’ Matrices look like grids. See Figure 12.1. 199 chapter 12 Each slot in the grid has a numbered location, and this is why matrices are a good place to store data. See Figure 12.2. Each of the locations is unique because of the row and column, which vary for each slot. Look at slot 1,1 and think of it as the first member in the first row and first column. If you look at the slot just to the right of it, it is numbered 1,2. You can think of this as the second member in the first row. Slot 1,3 is the third member in the first row. If you skip down to slot 3,1 you can think of this member as the first member in the third row. Now let’s give a name to this matrix, just as we gave a name to the arrays we examined. We could call it Student. See Figure 12.3 for one interpretation of the grid. Note that the grid serves to illustrate how the values in a matrix are organized. Each student is identified by the two numbers, which could represent where they sit in the class. Student 1,1 is the first student in the first row while Student 2,1 is the first student in the second row. Then Student 3,2 must be the second student in the third row. See Figure 12.4. As mentioned earlier, computers lack imagination. It’s easier to use numbers to identify elements than individual names. 200 Chapter 12 n The Matrix—Before the Movie Figure 12.1 A two-dimensional grid with three rows an d four columns. Figure 12.2 Each slot has a unique location: its row followed by its column. Figure 12.3 The grid is shown filled with different students identified by their row and co lumn. [...]... Defining a Record Before you define a record, you need to think of a good name for the record’s contents Let’s name our record individual for the information we just mentioned The syntax for declaring a record will include braces { } to show where the record begins and ends Here is an example of a declaration in the programming language C++ A record in C++ is called a struct, short for ‘‘structure,’’... understanding what a matrix is in computer programming will make it easier for you to understand its use in algebra Let’s revisit the Student matrix we talked about Note In most computer languages, a matrix has a row 0 and a column 0 We have ignored that to simplify the discussion See the programs on the CD for examples of those matrices Let’s look at how each member would be named in a computer language Name... have informed the computer what kind of data holder we need and how many slots of memory we need as well In the example with the Student matrix, the computer has to set aside enough storage to hold 12 different strings Each string will take a fixed number of bytes for storage, so 12 of those strings will take 12 times that number bytes of memory Recall that that is the most important reason for declaration... variables: we need to tell the computer how much memory it should set aside, or allocate, for the data we have In the other example, where we declared the group matrix, we needed to have 24 slots, all with the common name of group and each holding an integer If each integer needs 2 bytes for storage, then 24 of those integers will take 48 bytes of storage, and the computer will look for 48 sequential free... well as the number we want to store into the matrix for( int x = 1; x . nested for loops to load the matrix. The term nested means that we will put one for loop inside the other. Before I explain what this does, look at this code: for ( int x = 1; x <= 5; x++ ) for. separately, let’s use a for loop to hit each of the members in row 1. Here is the for loop that will do that. for (int x = 1; x <= 4; x++ ) { group[1][x] = 5; } Ihaveonlyusedonefor loop just so that. subscript. Nested For Loops Before we examine the array further, let’s look at nested for loops, which will prove very useful in working with a matrix. There are two loops in a nested for loop: the