Week 4 Classwork

Redeem Lame Chars

  #include <iostream>
  #include <string>
  #include <cassert>
  using namespace std;
    
  /*
  * Returns whether or not the character code if c
  * is less than i.
  */
  bool isLameChar (char c, int i) {
      return c < i;
  }
    
  /*
  * Returns a string that is equal to s with all chars
  * whose code is less than i replaced with r
  */
  string redeemLameChars (string s, int i, char r) {
      for (int j = 0; j < s.length(); j++) {
          // [!] If we meet our isLameChar criteria...
          if (isLameChar(s[j], i)) {
              // ...then replace the current letter with r
              s[j] = r;
          }
      }
      // Return that string with replacement
      return s;
  }
    
  int main () {
      cout << redeemLameChars("abc", 1, '!') << endl;
      cout << redeemLameChars("abc", 100, '!') << endl;
      cout << redeemLameChars("C00L", '9', '!') << endl;
  }


Excitement Thief

  #include <iostream>
  #include <string>
  using namespace std;
    
  /*
  * Takes in a string by reference and then removes all exclamation
  * points from it.
  */
  void excitementThief (string& s) {
      for (int i = 0; i < s.length(); i++) {
          // [!] If the current character is an exclamation
          // point...
          if (s[i] == '!') {
              // [!] ...then remove that character using the
              // the substr function
              s = s.substr(0, i) + s.substr(i + 1);
                
              // [!] We need to do one more thing for this
              // to work below...
              i--;
          }
      }
  }
    
  int main () {
      string s = "test!ing",
              t = "tes!!!t!i!ng",
              r = "!!!";
    
      excitementThief(s);
      excitementThief(t);
      excitementThief(r);
        
      // "testing"
      cout << s << endl;
      // "testing"
      cout << t << endl;
      // ""
      cout << r << endl;
  }