#include #include using std::string; using std::cout; using std::endl; string makeString(int n); int countX(const string& s); int countXTail(const string& s, std::string::size_type n, int tot); void lengthen(string& s); int main() { string s1 = makeString(10000); cout << "done" << endl; cout << countX(s1) << endl; auto name = std::string{"Jim"}; lengthen(name); cout << name << endl; } /** * Creates a string containing n x's. */ string makeString(int n) { string s; for (int i = 0; i < n; i++) { s += 'x'; // C++ strings are mutable; build char-by-char using append } return s; } /** * Counts the number of 'x' characters in s. */ int countX(const string& s) { // note use of reference parameter const string& to avoid copie // required for call-by-value return countXTail(s, 0, 0); // call recursive helper function } int countXTail(const string& s, std::string::size_type n, int tot) { // tail recursion not optimized to a loop by default; this code // will crash b/c it runs out of stack space for long strings // (g++ has option to turn on tail-recursion optimization) if (n == s.length()) { return tot; } else if (s[n] == 'x') { return countXTail(s, n + 1, tot + 1); } else { return countXTail(s, n + 1, tot); } } void lengthen(string& s) { // here we use the (non-const) reference parameter b/c the function // is supposed to change the string that is passed to it s += 'x'; }