⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chapter07.html

📁 think like a computer scientist
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<HTML><HEAD>  <TITLE>Chapter 7</TITLE>  <LINK REL="STYLESHEET" HREF="downey.css" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/downey.css"></HEAD><BODY><H2>Chapter 7</H2><H1>Strings and things</H1><BR><BR><H3>7.1 Containers for strings</H3><P>We have seen five types of values---booleans, characters, integers, floating-point numbers and strings---but only four types of variables---<TT>bool</TT>, <TT>char</TT>, <TT>int</TT> and <TT>double</TT>.  So far we haveno way to store a string in a variable or perform operations on strings.</P><P>In fact, there are several kinds of variables in C++ that can store strings.One is a basic type that is part of the C++ language, sometimes called ``a native C string.''  The syntax for C strings is a bit ugly, and using them requires some concepts we have not covered yet, so for the most part we are going to avoid them.</P><P>The string type we are going to use is called <TT>apstring</TT>, which is a type created specifically for the Computer Science AP Exam.</P><BLOCKQUOTE><B>note</B>: In order for me to talk about AP classes in this book, I have to include the following text:  <BLOCKQUOTE>  ``Inclusion of the C++ classes defined for use in the Advanced Placement   Computer Science courses does not constitute endorsement of the other   material in this textbook by the College Board, Educational Testing service,   or the AP Computer Science Development Committee. The versions of the C++   classes defined for use in the AP Computer Science courses included in this   textbook were accurate as of 20 July 1999.  Revisions to the classes may   have been made since that time.''  </BLOCKQUOTE>Since both the text and sample programs in this book are licensed under the GPL, Jonah Cohen has supplied free classes which are call compatible with theunfree ones from the college board.  To find out more about these <I>pclasses</I>, click <A HREF="javascript:if(confirm('http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/pclasses  \n\nThis file was not retrieved by Teleport Pro, because it was redirected to an invalid location.  You should report this problem to the site\'s webmaster.  \n\nDo you want to open it from the server?'))window.location='http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/pclasses'" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/pclasses">here</A>. </BLOCKQUOTE><P>You might be wondering what they mean by <B>class</B>. It will be a few more chapters before I can give a complete definition, but for now a class is a collection of functions that defines the operations we can perform on some type.  The <TT>apstring</TT> class contains all the functions that apply to <TT>apstring</TT>s.</P><P>Unfortunately, it is not possible to avoid C strings altogether. In a few places in this chapter I will warn you about some problems you might run into using <TT>apstring</TT>s instead of C strings.</P><BR><BR><H3>7.2 <TT>apstring</TT> variables</H3><P>You can create a variable with type <TT>apstring</TT> in the usual ways:</P><PRE>  apstring first;  first = "Hello, ";  apstring second = "world.";</PRE><P>The first line creates an <TT>apstring</TT> without giving it a value. The second line assigns it the string value <TT>"Hello."</TT> The third line is a combined declaration and assignment, also called an initialization.</P><P>Normally when string values like <TT>"Hello, "</TT> or <TT>"world."</TT> appear, they are treated as C strings.  In this case, when we assign them to an <TT>apstring</TT> variable, they are converted automatically to <TT>apstring</TT> values.</P><P>We can output strings in the usual way:</P><PRE>  cout << first << second << endl;</PRE><P>In order to compile this code, you will have to include the header file for the <TT>apstring</TT> class, and you will have to add the file <TT>apstring.cpp</TT> to the list of files you want to compile. The details of how to do this depend on your programming environment.</P><P>Before proceeding, you should type in the program above and make sure you can compile and run it.</P><BR><BR><H3>7.3 Extracting characters from a string</H3><P>Strings are called ``strings'' because they are made up of a sequence, or string, of characters.  The first operation we are going to perform on a stringis to extract one of the characters.  C++ uses square brackets (<TT>[</TT> and <TT>]</TT>) for this operation:</P><PRE>  apstring fruit = "banana";  char letter = fruit[1];  cout << letter << endl;</PRE><P>The expression <TT>fruit[1]</TT> indicates that I want character number 1 from the string named <TT>fruit</TT>.  The result is stored in a <TT>char</TT> named <TT>letter</TT>.  When I output the value of <TT>letter</TT>, I get a surprise:</P><PRE>a</PRE><P><TT>a</TT> is not the first letter of <TT>"banana"</TT>. Unless you are acomputer scientist. For perverse reasons, computer scientists always start counting from zero. The 0th letter (``zeroeth'') of <TT>"banana"</TT> is <TT>b</TT>. The 1th letter (``oneth'') is <TT>a</TT> and the 2th (``twoeth'') letter is <TT>n</TT>.</P><P>If you want the the zereoth letter of a string, you have to put zero in the square brackets:</P><PRE>  char letter = fruit[0];</PRE><BR><BR><H3>7.4 Length</H3><P>To find the length of a string (number of characters), we can use the <TT>length</TT> function. The syntax for calling this function is a little different from what we've seen before:</P><PRE>  int length;  length = fruit.length();</PRE><P>To describe this function call, we would say that we are <B>invoking</B> thelength function on the string named <TT>fruit</TT>.  This vocabulary may seem strange, but we will see many more examples where we invoke a function on an object.  The syntax for function invocation is called ``dot notation,'' becausethe dot (period) separates the name of the object, <TT>fruit</TT>, from the name of the function, <TT>length</TT>.</P><TT>length</TT> takes no arguments, as indicated by the empty parentheses<TT>()</TT>.  The return value is an integer, in this case 6.  Notice that it is legal to have a variable with the same name as a function.</P><P>To find the last letter of a string, you might be tempted to try something like</P><PRE>  int length = fruit.length();  char last = fruit[length];       // WRONG!!</PRE><P>That won't work. The reason is that there is no 6th letter in <TT>"banana"</TT>. Since we started counting at 0, the 6 letters are numbered from 0 to 5.  To get the last character, you have to subtract 1 from <TT>length</TT>.</P><PRE>  int length = fruit.length();  char last = fruit[length-1];</PRE><BR><BR><H3>7.5 Traversal</H3><P>A common thing to do with a string is start at the beginning, select each character in turn, do something to it, and continue until the end.  This pattern of processing is called a <B>traversal</B>. A natural way to encode a traversal is with a <TT>while</TT> statement:</P><PRE>  int index = 0;  while (index &lt; fruit.length()) {    char letter = fruit[index];    cout << letter << endl;    index = index + 1;  }</PRE><P>This loop traverses the string and outputs each letter on a line by itself.Notice that the condition is <TT>index &lt; fruit.length()</TT>, which means that when <TT>index</TT> is equal to the length of the string, the condition isfalse and the body of the loop is not executed. The last character we access isthe one with the index <TT>fruit.length()-1</TT>.</P><P>The name of the loop variable is <TT>index</TT>. An <B>index</B> is a variable or value used to specify one member of an ordered set, in this case the set of characters in the string. The index indicates (hence the name) whichone you want. The set has to be ordered so that each letter has an index and each index refers to a single character.</P><P>As an exercise, write a function that takes an <TT>apstring</TT> as an argument and that outputs the letters backwards, all on one line.</P><BR><BR><H3>7.6 A run-time error</H3><P>Way back in Section 1.3.2 I talked about run-time errors, which are errors that don't appear until a program has started running.</P><P>So far, you probably haven't seen many run-time errors, because we haven't been doing many things that can cause one.  Well, now we are. If you use the <TT>[]</TT> operator and you provide an index that is negative or greater than <TT>length-1</TT>, you will get a run-time error and a message something like this:</P><PRE>index out of range: 6, string: banana</PRE><P>Try it in your development environment and see how it looks.</P><BR><BR><H3>7.7 The <TT>find</TT> function</H3><P>The <TT>apstring</TT> class provides several other functions that you can invoke on strings. The <TT>find</TT> function is like the opposite the <TT>[]</TT> operator. Instead of taking an index and extracting the character at that index, <TT>find</TT> takes a character and finds the index where that character appears.</P><PRE>  apstring fruit = "banana";  int index = fruit.find('a');</PRE><P>This example finds the index of the letter <TT>'a'</TT> in the string. In this case, the letter appears three times, so it is not obvious what <TT>find</TT> should do.  According to the documentation, it returns the index of the <I>first</I> appearance, so the result is 1. If the given letter does not appear in the string, <TT>find</TT> returns -1.</P><P>In addition, there is a version of <TT>find</TT> that takes another <TT>apstring</TT> as an argument and that finds the index where the substringappears in the string.  For example,</P><PRE>  apstring fruit = "banana";  int index = fruit.find("nan");</PRE><P>This example returns the value 2.</P><P>You should remember from Section 5.4 that there can be more than one function with the same name, as long as they take a different number of parameters or different types. In this case, C++ knows which version of <TT>find</TT> to invoke by looking at the type of the argument we provide.</P><BR><BR><H3>7.8 Our own version of <TT>find</TT></H3><P>If we are looking for a letter in an <TT>apstring</TT>, we may not want to start at the beginning of the string. One way to generalize the <TT>find</TT> function is to write a version that takes an additional parameter---the index where we should start looking. Here is an implementation of this function.</P><PRE>int find (apstring s, char c, int i){  while (i &lt; s.length()) {    if (s[i] == c) return i;    i = i + 1;  }  return -1;}</PRE><P>Instead of invoking this function on an <TT>apstring</TT>, like the first version of <TT>find</TT>, we have to pass the <TT>apstring</TT> as the first argument. The other arguments are the character we are looking for and the index where we should start.</P><BR><BR><H3>7.9 Looping and counting</H3><P>The following program counts the number of times the letter <TT>'a'</TT> appears in a string:</P><PRE>  apstring fruit = "banana";  int length = fruit.length();  int count = 0;  int index = 0;  while (index < length) {    if (fruit[index] == 'a') {      count = count + 1;    }    index = index + 1;  }  cout << count << endl;</PRE><P>This program demonstrates a common idiom, called a <B>counter</B>. The variable <TT>count</TT> is initialized to zero and then incremented each time we find an <TT>'a'</TT>.  (To <B>increment</TT> is to increase by one; it is the opposite of <B>decrement</B>, and unrelated to <B>excrement</B>, which is anoun.)  When we exit the loop, <TT>count</TT> contains the result: the total number of a's.</P><P>As an exercise, encapsulate this code in a function named <TT>countLetters</TT>, and generalize it so that it accepts the string and the letter as arguments.</P>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -