7.8. Our own version of find

If we are looking for a letter in a string, we may not want to start at the beginning of the string. One way to generalize the find function is to write a version that takes an additional parameter—the index where we should start looking. Here is an implementation of this function.

size_t find (string s, char c, size_t i) {
  while (i < s.length()) {
    if (s[i] == c) return i;
    i = i + 1;
  }
  return string::npos;
}

Instead of invoking this function on an string, like the first version of find, we have to pass the string as the first argument. The other arguments are the character we are looking for and the index where we should start.

In the active code below, we are finding the number of 'e' characters in the “Shepard” part of “German Shepard” using our function. Then we use the built-in find function to demonstrate how they work differently.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 3 activities on this page