Assignment 8

Lab assignment 8 is available on the moodle for your practice. Please note that this is an ungraded assignment.

We encourage you to do these ungraded assignments by yourself until the end, as this will help you to improve your coding skills.

  1. Strings: What is the output of the following code?
    void mystery(string a, string &b)
    {
      a.erase(0, 1);
      b += a[0];
      b.insert(3, "FOO");
    }
    
    int main()
    {
      string a = "thomas";
      string b = "edison";
      mystery(a, b);
      cout << a << " " << b << endl;
      return 0;
    }
    
    Explain.
  2. Remove odd index characters: Write a program that removes the characters at the odd indices. Examples: Notice that only characters at the even indices remain in the output. The characters at the odd indices of the input have been removed in the output.
  3. Checking palindromes: A palindrome is a string that is spelled the same when reversed. For example: MALAYALAM is a palindrome, because the reverse of this string is also MALAYALAM. Similarly, madam and AbbA are palindromes.

    Write a method checkPalindrome(string const &s) that takes a string parameter (s) and returns the boolean value TRUE if s is a palindrome; otherwise it returns FALSE. Also, write the main function similar to what is shown below to read user input repeatedly (until a sentinel value) and check if the input line is a palindrome or not.

    bool checkPalindrome(string const &s)
    {
      //your code here
    }
    
    int main()
    {
      while (1) {
        string line;
        line = getLine("Enter next string to be checked: ");
        if (line == "") {
          break;
        }
        if (checkPalindrome(line)) {
          cout << "Yes, " << line << " is a palindrome." << endl;
        } else {
          cout << "No, " << line << " is not a palindrome." << endl;
        }
      }
    }
    
    Test your program with multiple inputs. Also answer the following questions:
    1. The string parameter to checkPalindrome() is a const parameter? Would it be okay to change this to pass-by-value? Would it be okay to change this to (non-const) pass-by-reference? What are the considerations which allow us to choose one over another?
  4. Count substrings: Given two strings, count the number of times the first string appears in the second (as a substring). It should also print the indices at which the first string appears in the second string. You also need to consider overlapping appearances. Examples: