C++: C-String Exercises - 2

Write the following functions. Note that all input and output must be in the main function, not in these functions. You may not have any I/O (cin / cout) in a function, except during debugging of that function. This is a good programming style that is used by most programs: the I/O should be concentrated in a very few functions which are used specifically for printing. Also, do not use temporary arrays. All of these arrays can be changed in-place, without declaring an extra array.

  1. Write a function to remove all trailing blanks from the right end of a string. Assume the prototype is
    void trimRight(char a[]);
  2. Write a function to remove all leading blanks from the left end of a string. Assume the prototype is
    void trimLeft(char a[]);
  3. Write a function to add extra blanks to the right end of a string to make it at least length n. If the string is already n characters or longer, do not change the string. Assume the prototype is
    void padRight(char a[], int n);
  4. Write a function to add extra blanks to the left end of a string to make it at least length n. If the string is already n characters or longer, do not change the string. Assume the prototype is
    void padLeft(char a[], int n);
  5. Write a function to center a string by adding blanks to the front and back. If the string is already n characters or longer, do not change the string. If an odd number of blanks have to be added, put the extra blank on the right. You can use the functions in the previous problems (padRight and padLeft) to solve this problem. Assume the prototype is
    void center(char a[], int n);
  6. Write a function which returns non-zero (ie, true) if the string parameter is a palindrome. A palindrome is any "word" which is the same forward and backward, eg, radar, noon, 20011002... The function should return 0 if the argument is not a palindrome. Assume the prototype is
    int isPalindrome(char a[]);
  7. Write a function which shortens a string to n characters. If the string is shorter than n, the function should not change the string. Assume the prototype is
    void truncate(char a[], int n);
  8. Write a function which capitalizes the first letter in every word. Assume the first letter is any letter at the beginning or preceded by a blank. All other letters should be turned into lowercase. You can use the library toupper and tolower functions. Assume the prototype is
    void capitalizeWords(char a[]);
Solutions: cstring_exercises.cpp This is not an HTML file, so clicking on it may start your C++ compiler. To save the file without starting the compiler, use right-click. From the popup menu select "Save Target As..." in Internet Explorer, "Save as..." in new versions of Netscape, or "Open in New Window" and then select the save to file option in Netscape 4.7.