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

📄 chapter07.html

📁 think like a computer scientist
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<P>As a second exercise, rewrite this function so that instead of traversing the string, it uses the version of <TT>find</TT> we wrote in the previous section.</P><BR><BR><H3>7.10 Increment and decrement operators</H3><P>Incrementing and decrementing are such common operations that C++ provides special operators for them. The <TT>++</TT> operator adds one to the current value of an <TT>int</TT>, <TT>char</TT> or <TT>double</TT>, and <TT>--</TT> subtracts one.  Neither operator works on <TT>apstring</TT>s, and neither <I>should</TT> be used on <TT>bool</TT>s.</P><P>Technically, it is legal to increment a variable and use it in an expression at the same time.  For example, you might see something like:</P><PRE>  cout << i++ << endl;</PRE><P>Looking at this, it is not clear whether the increment will take effect before or after the value is displayed.  Because expressions like this tend to be confusing, I would discourage you from using them. In fact, to discourage you even more, I'm not going to tell you what the result is.  If you really want to know, you can try it.</P><P>Using the increment operators, we can rewrite the letter-counter:</P><PRE>  int index = 0;  while (index < length) {    if (fruit[index] == 'a') {      count++;    }    index++;  }</PRE><P>It is a common error to write something like</P><PRE>  index = index++;             // WRONG!!</PRE><P>Unfortunately, this is syntactically legal, so the compiler will not warn you.  The effect of this statement is to leave the value of <TT>index</TT> unchanged. This is often a difficult bug to track down.</P><P>Remember, you can write <TT>index = index +1;</TT>, or you can write <TT>index++;</TT>, but you shouldn't mix them.</P><BR><BR><H3>7.11 String concatenation</H3><P>Interestingly, the <TT>+</TT> operator can be used on strings; it performs string <B>concatenation</B>. To concatenate means to join the two operands end to end.  For example:</P><PRE>  apstring fruit = "banana";  apstring bakedGood = " nut bread";  apstring dessert = fruit + bakedGood;  cout << dessert << endl;</PRE><P>The output of this program is <TT>banana nut bread</TT>.</P><P>Unfortunately, the <TT>+</TT> operator does not work on native C strings, soyou cannot write something like</P><PRE>  apstring dessert = "banana" + " nut bread";</PRE><P>because both operands are C strings.  As long as one of the operands is an <TT>apstring</TT>, though, C++ will automatically convert the other.</P><P>It is also possible to concatenate a character onto the beginning or end of an <TT>apstring</TT>.  In the following example, we will use concatenation and character arithmetic to output an abecedarian series.</P><P>``Abecedarian'' refers to a series or list in which the elements appear in alphabetical order.  For example, in Robert McCloskey's book <I>Make Way for Ducklings</I>, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack and Quack.  Here is a loop that outputs these names in order:</P><PRE>  apstring suffix = "ack";  char letter = 'J';  while (letter <= 'Q') {    cout << letter + suffix << endl;    letter++;  }</PRE><P>The output of this program is:</P><PRE>JackKackLackMackNackOackPackQack</PRE><P>Of course, that's not quite right because I've misspelled ``Ouack'' and ``Quack.''  As an exercise, modify the program to correct this error.</P><P>Again, be careful to use string concatenation only with <TT>apstring</TT>sand not with native C strings.  Unfortunately, an expression like <TT>letter + "ack"</TT> is syntactically legal in C++, although it produces a very strange result, at least in my development environment.</P><BR><BR><H3>7.12 <TT>apstring</TT>s are mutable</H3><P>You can change the letters in an <TT>apstring</TT> one at a time using the <TT>[]</TT> operator on the left side of an assignment. For example,</P><PRE>  apstring greeting = "Hello, world!";  greeting[0] = 'J';  cout << greeting << endl;</PRE><P>produces the output <TT>Jello, world!</TT>.</P><BR><BR><H3>7.13 <TT>apstring</TT>s are comparable</H3><P>All the comparison operators that work on <TT>int</TT>s and <TT>double</TT>s also work on <TT>apstrings</TT>.  For example, if you want to know if two strings are equal:</P><PRE>  if (word == "banana") {    cout << "Yes, we have no bananas!" << endl;  }</PRE><P>The other comparison operations are useful for putting words in alphabeticalorder.</P><PRE>  if (word < "banana") {    cout << "Your word, " << word << ", comes before banana." << endl;  } else if (word > "banana") {    cout << "Your word, " << word << ", comes after banana." << endl;  } else {    cout << "Yes, we have no bananas!" << endl;  }</PRE><P>You should be aware, though, that the <TT>apstring</TT> class does not handle upper and lower case letters the same way that people do. All the upper case letters come before all the lower case letters.  As a result,</P><PRE>Your word, Zebra, comes before banana.</PRE><P>A common way to address this problem is to convert strings to a standard format, like all lower-case, before performing the comparison. The next sections explains how. I will not address the more difficult problem, which is making the program realize that zebras are not fruit.</P><BR><BR><H3>7.14 Character classification</H3><P>It is often useful to examine a character and test whether it is upper or lower case, or whether it is a character or a digit. C++ provides a library of functions that perform this kind of character classification. In order to use these functions, you have to include the header file <TT>ctype.h</TT>.</P><PRE>  char letter = 'a';  if (isalpha(letter)) {    cout << "The character " << letter << " is a letter." << endl;  }</PRE><P>You might expect the return value from <TT>isalpha</TT> to be a <TT>bool</TT>, but for reasons I don't even want to think about, it is actuallyan integer that is 0 if the argument is not a letter, and some non-zero valueif it is.</P><P>This oddity is not as inconvenient as it seems, because it is legal to use this kind of integer in a conditional, as shown in the example. The value 0 is treated as <TT>false</TT>, and all non-zero values are treated as <TT>true</TT>.</P><P>Technically, this sort of thing should not be allowed---integers are not the same thing as boolean values. Nevertheless, the C++ habit of converting automatically between types can be useful.</P><P>Other character classification functions include <TT>isdigit</TT>, which identifies the digits 0 through 9, and <TT>isspace</TT>, which identifies all kinds of ``white'' space, including spaces, tabs, newlines, and a few others.There are also <TT>isupper</TT> and <TT>islower</TT>, which distinguish upper and lower case letters.</P><P>Finally, there are two functions that convert letters from one case to the other, called <TT>toupper</TT> and <TT>tolower</TT>. Both take a single character as a parameter and return a (possibly converted) character.</P><PRE>  char letter = 'a';  letter = toupper (letter);  cout << letter << endl;</PRE><P>The output of this code is <TT>A</TT>.</P><P>As an exercise, use the character classification and conversion library to write functions named <TT>apstringToUpper</TT> and <TT>apstringToLower</TT> that take a single <TT>apstring</TT> as a parameter, and that modify the string by converting all the letters to upper or lower case. The return type should be <TT>void</TT>.</P><BR><BR><H3>7.15 Other <TT>apstring</TT> functions</H3><P>This chapter does not cover all the <TT>apstring</TT> functions. Two additional ones, <TT>c\_str</TT> and <TT>substr</TT>, are covered in Section 15.2 and Section 15.4.</P><BR><BR><H3>7.16 Glossary</H3><DL>  <DT>object:</DT><DD> A collection of related data that comes with a set of  functions that operate on it.  The objects we have used so far are the  <TT>cout</TT> object provided by the system, and <TT>apstring</TT>s.</DD>  <DT>index:</DT><DD> A variable or value used to select one of the members of   an ordered set, like a character from a string.</DD>  <DT>traverse:</DT><DD> To iterate through all the elements of a: set   performing a similar operation on each.</DD>  <DT>counter:</DT><DD> A variable used to count something, usually initialized  to zero and then incremented.</DD>  <DT>increment:</DT><DD> Increase the value of a variable by one. The   increment operator in C++ is <TT>++</TT>. In fact, that's why C++ is called   C++, because it is meant to be one better than C.</DD>  <DT>decrement:</DT><DD> Decrease the value of a variable by one. The   decrement operator in C++ is <TT>--</TT>.</DD>  <DT>concatenate:</DT><DD>To join two operands end-to-end.</DD></DL><BR><DIV CLASS=navigation><HR>  <TABLE ALIGN=center WIDTH="100%" CELLPADDING=0 CELLSPACING=2>  <TR>    <TD><A HREF="chapter08.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter08.html">      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="next"       SRC="images/next.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/next.gif"></A>    </TD>    <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html">      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="up"       SRC="images/up.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/up.gif"></A>    </TD>    <TD><A HREF="chapter06.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter06.html">      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="previous"      SRC="images/previous.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/previous.gif"></A>    </TD>    <TD ALIGN=center BGCOLOR="#99CCFF" WIDTH="100%">      <B CLASS=title>How to Think Like a Computer Scientist: Chapter 7</B>    </TD>    <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html">      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="contents"      SRC="images/contents.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/contents.gif"></A>    </TD>    <TD>      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT=""      SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif">    </TD>    <TD>      <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT=""      SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif">    </TD>  </TR>  </TABLE>  <B CLASS=navlabel>Next:</B>  <SPAN CLASS=sectref><A HREF="chapter08.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter08.html">Chapter 8</A></SPAN>  <B CLASS=navlabel>Up:</B>  <SPAN CLASS=sectref><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html">Index</A></SPAN>  <B CLASS=navlabel>Previous:</B>  <SPAN CLASS=sectref><A HREF="chapter06.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter06.html">Chapter 6</A></SPAN>  <HR></DIV></BODY></HTML>

⌨️ 快捷键说明

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