Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Exercises 7.19 Coding Practice

1.

A palindrome is a word, phrase, or sentence that reads the same forwards and backwards.
Write a function isPalindrome that takes a string input as a parameter and returns a boolean that is true if the input is a palindrome and false otherwise. Run and test your code!
Solution.
Below is one way to implement the program. We use the isalpha function to ignore the non alphabetical characters. Then we continuously check to see if the letters in the front are equal to the ones in the back until we reach the middle of the string.
#include <iostream>
#include <cctype>
using namespace std;

bool isPalindrome(string input) {
    size_t front = 0;
    size_t back = input.length() - 1;
    while (front < back) {
        while (!isalpha(input[front])) {
            front++;
        }
        while (!isalpha(input[back])) {
            back--;
        }
        if (input[front] != input[back]) {
            return false;
        }
        front++;
        back--;
    }
    return true;
}

2.

How much does Bubba love shrimp? Probably a lot. But how many times does the word “shrimp” come up in his monologue? Write a function countWord that counts the number of times a given word appears in a given string. countWord should take two strings input and word as parameters and return an int. Feel free to use the stringToLower function we wrote earlier. Check the hint below for help with the construction of the code.
Hint.

Activity 7.19.1.

How much does Bubba love shrimp? Probably a lot. But how many times does the word “shrimp” come up in his monologue? Write a function countWord that counts the number of times a given word appears in a given string. countWord should take two strings input and word as parameters and return an int. Feel free to use the stringToLower function we wrote earlier. Use the lines to construct the code, then go back to complete the Activecode.

3.

Write a void function censorWord that censors a given word from a given string and prints out the new string. censorWord should take two strings input and word as parameters and prints out input with every occurence of word censored with asterisks. For example, censorWord("I really, really, really, really, really, really like you", "really") results in the following output:
I ******, ******, ******, ******, ******, ****** like you
Solution.
Below is one way to implement the program. We use a while loop to repeatedly search for instances of word in input. Once found, we replace the length of the word with asterisks.
#include <iostream>
using namespace std;

void censorWord(string input, string word) {
    size_t length = word.length();
    while (input.find(word) != string::npos) {{
        int index = input.find(word);
        size_t i = 0;
        while (i < length) {
            input[index + i] = '*';
            i++;
        }
    }
    cout << input;
}

int main() {
    censorWord("I really, really, really, really, really, really like you", "really");
}

4.

Write a void function removeWord that removes a given word from a given string and prints out the new string. removeWord should take two strings input and word as parameters and prints out input with every occurence of word removed. Use string concatenation and the C++ string function substr. substr takes two parameters, a starting index and a length. For example, if string greeting = "hello world", then greeting.substr(6, 5) returns the string "world". Test your function in main. Check the hint below for help with the construction of the code. The output should be:
Gucci , Gucci , Gucci , Gucci
Hint.

Activity 7.19.2.

Write a void function removeWord that removes a given word from a given string and prints out the new string. removeWord should take two strings input and word as parameters and prints out input with every occurence of word removed. Use string concatenation and the C++ string function substr. substr takes two parameters, a starting index and a length. For example, if string greeting = "hello world", then greeting.substr(6, 5) returns the string "world". Test your function in main. Use the lines to construct the code, then go back to complete the Activecode. The output should be:
Gucci , Gucci , Gucci , Gucci

5.

ROT13 is a simple letter substitution cipher that shifts every letter forward by 13, looping around if necessary. For example, the letter ’a’, 1st in the alphabet, becomes the letter ’n’, 14th in the alphabet. The letter ’r’, 18th in the alphabet, becomes the letter ’e’, 5th in the alphabet. Since the alphabet has 26 letters and 13 is exactly half, a message encrypted using ROT13 can be decrypted by calling ROT13 on the encrypted message.
Write the function ROT13 , which takes a string input as a parameter and returns an encrypted string . Test your function in main .
Solution.
Below is one way to implement the ROT13 function. We use a while loop to go through all the letters in the string. If the letter is between ‘a’ and ‘n’ or ‘A’ and ‘N’, we use character operations to add 13 to each letter. Otherwise, we subtract 13 from each letter. We return the encrypted message at the end.
#include <iostream>
#include <cctype>
using namespace std;

string ROT13(string input) {
    size_t n = 0;
    while (n < input.length()) {
        if (isalpha(input[n])) {
            if ((input[n] >= 'a' && input[n] < 'n') || (input[n] >= 'A' && input[n] < 'N')) {
                input[n] = input[n] + 13;
            }
            else {
                input[n] = input[n] - 13;
            }
        }
        n++;
    }
    return input;
}

int main() {
    string original = "Encrypt me then decrypt me!";
    string encrypted = ROT13 (original);
    string decrypted = ROT13 (encrypted);
    cout << "Original string: " << original << endl;
    cout << "Encrypted string: " << encrypted << endl;
    cout << "Decrypted string: " << decrypted << endl;

    // Uncomment and run the code below once your function works!
    // string secretMessage = "Pbatenghyngvbaf! Lbh'ir fhpprffshyyl vzcyrzragrq EBG13 naq qrpbqrq gur frperg zrffntr :)";
    // cout << ROT13 (secretMessage) << endl;
}

6.

Write the function reverseWord which takes a string input, reverses it, and returns the reversed string. Run and test your code! Check the hint below for help with the construction of the code.
Hint.

Activity 7.19.3.

Write the function reverseString which takes a string input, reverses it, and returns the reversed string. Use the lines to construct the code, then go back to complete the Activecode.

7.

Write the function capitalize , which takes a string input as a parameter. capitalize capitalizes the first letter of every word, and returns the new string .
Solution.
Below is one way to implement the capitalize function. We use a while loop to go through all the chars in the string. We capitalize the first character and all characters following a space using toupper. At the end, we return the string.
#include <iostream>
#include <cctype>
using namespace std;

string capitalize(string input) {
    size_t n = 0;
    while (n < input.length()) {
        if (n == 0) {
            input[n] = toupper(input[n]);
        }
        else if (input[n-1] == ' ') {
            input[n] = toupper(input[n]);
        }
        n++;
    }
    return input;
}

int main() {
    cout << capitalize ("every word in this string should be capitalized!") << endl;
    cout << capitalize ("this String As well") << endl;
}

8.

Write the function countVowels which takes a string input and returns the number of vowels in the string. Remember, ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ are vowels. Run and test your code! Check the hint below for help with the construction of the code.
Hint.

Activity 7.19.4.

Write the function countVowels which takes a string input and returns the number of vowels in the string. Remember, ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ are vowels. Use the lines to construct the code, then go back to complete the Activecode.

9.

Write the function longestWord , which takes a string input as a parameter. longestWord returns the words with the most letters in input . If there’s a tie, return the first word. Use the substr function. Run and test your code!
Solution.
Below is one way to implement the longestWord function. We use a while loop to go through all the chars in the string. We use variables to keep track of the longest word, the longest amount of letters, and the length of the current word. We can determine the length of a word by counting the number of chars between spaces. If the length is greater than the max, length becomes the new max and we update the longest word. This keeps repeating until we reach the end of the string, and the longest word is returned.
#include <iostream>
using namespace std;

string longestWord(string input) {
    size_t n = 0;
    size_t maxLength = 0;
    while (n < input.length()) {
        size_t wordLength = 0;
        while (input[n] != ' ' && n < input.length()) {
            wordLength++;
            n++;
        }
        if (wordLength > maxLength) {
            maxLength = wordLength;
            longest = input.substr(n - maxLength, maxLength);
        }
        n++;
    }
    return longest;
}

10.

Camel case is the practice of writing phrases without spaces or punctuation, indicating the separation of words using capital letter. For example, “camel case” in camel case is “camelCase”. Snake case is the practice of writing phrases where each space is replaced by an underscore. For example, “snake case” in snake case is “snake_case”. Write the functions snakeToCamel and camelToSnake. Each function takes a string input and returns the input using the other stylization. Feel free to use any string functions you’d like. Run and test your code! Check the hint below for help with the construction of the code.
Hint.

Activity 7.19.5.

Camel case is the practice of writing phrases without spaces or punctuation, indicating the separation of words using capital letter. For example, “camel case” in camel case is “camelCase”. Snake case is the practice of writing phrases where each space is replaced by an underscore. For example, “snake case” in snake case is “snake_case”. Write the functions snakeToCamel and camelToSnake. Each function takes a string input and returns the input using the other stylization. Feel free to use any string functions you’d like. Use the lines to construct the code, then go back to complete the Activecode.
You have attempted 1 of 16 activities on this page.