Programming in C

(Barry) #1

232 Chapter 10 Character Strings


to be inserted, and the position in the source string where the string is to be
inserted. So, the call
insertString (text, "per", 10);

with textas originally defined in the previous exercise, results in the character
string "per" being inserted inside text, beginning at text[10].Therefore, the
character string "the wrong person"is stored inside the textarray after the
function returned.


  1. Using the findString,removeString,and insertStringfunctions from preced-
    ing exercises, write a function called replaceStringthat takes three character
    string arguments as follows
    replaceString (source, s1, s2);


and that replaces s1inside source with the character string s2.The function
should call the findStringfunction to locate s1inside source, then call the
removeStringfunction to remove s1from source, and finally call the
insertStringfunction to insert s2into source at the proper location.
So, the function call
replaceString (text, "1", "one");

replaces the first occurrence of the character string "1"inside the character string
text, if it exists, with the string "one". Similarly, the function call
replaceString (text, "*", "");

has the effect of removing the first asterisk inside the textarray because the
replacement string is the null string.


  1. You can extend even further the usefulness of the replaceStringfunction from
    the preceding exercise if you have it return a value that indicates whether the
    replacement succeeded, which means that the string to be replaced was found
    inside the source string. So, if the function returns trueif the replacement suc-
    ceeds and falseif it does not, the loop
    do
    stillFound = replaceString (text, " ", "");
    while ( stillFound = true );
    could be used to remove allblank spaces from text, for example.
    Incorporate this change into the replaceStringsfunction and try it with various
    character strings to ensure that it works properly.

  2. Write a function called dictionarySortthat sorts a dictionary, as defined in
    Programs 10.9 and 10.10, into alphabetical order.

  3. Extend the strToIntfunction from Program 10.11 so that if the first character of
    the string is a minus sign, the value that follows is taken as a negative number.

Free download pdf