Programming in C

(Barry) #1

230 Chapter 10 Character Strings


The second time through the loop,intValueis set equal to 4, as calculated by sub-
tracting '0'from'4'. Multiplying resultby 10 produces 20, which is added to the
val ue of intValue,producing 24 as the value stored in result.
The third time through the loop,intValueis equal to '5' –'0', or 5, which is
added into the value of resultmultiplied by 10 (240).Thus, the value 245 is the value
of resultafter the loop has been executed for the third time.
Upon encountering the terminating null character, the forloop is exited and the
val ue of result, 245 , is returned to the calling routine.
The strToIntfunction could be improved in two ways. First, it doesn’t handle nega-
tive numbers. Second, it doesn’t let you know whether the string contained anyvalid
digit characters at all. For example,strToInt ("xxx")returns 0.These improvements
are left as an exercise.
This discussion concludes this chapter on character strings. As you can see, C provides
capabilities that enable character strings to be efficiently and easily manipulated.The
library actually contains a wide variety of library functions for performing operations on
strings. For example, it offers the function strlento calculate the length of a character
string,strcmpto compare two strings,strcatto concatenate two strings,strcpyto
copy one string to another,atoito convert a string to an integer, and isupper,
islower,isalpha,and isdigitto test whether a character is uppercase, lowercase,
alphabetic, or a digit. A good exercise is to rewrite the examples from this chapter to
make use of these routines. Consult Appendix B, “The Standard C Library,” which lists
many of the functions available from the library.

Exercises



  1. Type in and run the 11 programs presented in this chapter. Compare the output
    produced by each program with the output presented after each program in the
    text.

  2. Why could you have replaced the whilestatement of the equalStringsfunction
    of Program 10.4 with the statement
    while ( s1[i] == s2[i] && s1[i] != '\0' )


to achieve the same results?


  1. The countWordsfunction from Programs 10.7 and 10.8 incorrectly counts a word
    that contains an apostrophe as two separate words. Modify this function to correct-
    ly handle this situation. Also, extend the function to count a sequence of positive
    or negative numbers, including any embedded commas and periods, as a single
    word.

  2. Write a function called substringto extract a portion of a character string.The
    function should be called as follows:
    substring (source, start, count, result);

Free download pdf