Searching in strings

The find family of string member functions allows you to locate a character or group of characters within a given string.

String searching member functions and their general uses

The simplest use of find( ) searches for one or more characters in a string. This overloaded version of find( ) takes a parameter that specifies the character(s) for which to search and optionally a parameter that tells it where in the string to begin searching for the occurrence of a substring. (The default position at which to begin searching is 0.) By setting the call to find inside a loop, you can easily move through a string, repeating a search in order to find all the occurrences of a given character or group of characters within the string.

The following program uses the method of The Sieve of Erasthones to find prime numbers less than 50. This method starts with the number 2, marks all subsequent multiples of 2 as not prime, and repeats the process for the next prime candidate. Notice that we define the string object sieveChars using a constructor idiom that sets the initial size of the character array and writes the value ‘P’ to each of its member.

The find( ) function allows you to walk forward through a string, detecting multiple occurrences of a character or a group of characters, and find_first_not_of( ) allows you to find other characters or substrings.

There are no functions in the string class to change the case of a string, but you can easily create these functions using the Standard C library functions toupper( ) and tolower( ), which change the case of one character at a time. The following example illustrates a case-insensitive search:

Both the upperCase( ) and lowerCase( ) functions follow the same form: they make a copy of the argument string and change the case. The NewFind.cpp program isn’t the best solution to the case-sensitivity problem, so we’ll revisit it when we examine string comparisons.