Find character in string

Web Site  Methods

 
Str::Find
 
CPOS Find (STRCHAR ch, CPOS startat = 0) const

 
Str::FindNoCase
 
CPOS FindNoCase (STRCHAR ch, CPOS startat = 0) const

Find will search the string, starting at the given 0-based position (by default, the beginning of the string) and return the index of the first occurrence of the given character.  If the character cannot be found, the method returns -1.

If the startat parameter is beyond the end of the string, Str will throw an exception.

FindNoCase is exactly the same, but will do a case-insensitive search. It is somewhat slower, especially on big strings, so if you need to call it repeatedly in a performance-critical function, it is best to first produce a lowercase copy of the string and the character, and use Find() instead.

Example: simulate a case-insensitive search with Find

   Str somedata;
   STRCHAR somechar;
   // ... put values in somedata/somechar here ...
   Str data_copy(somedata);
   data_copy.MakeLower();
   STRCHAR char_copy = tolower(somechar);
   CPOS idx = 0;
   for (;;) {
      idx = data_copy.Find(char_copy, idx);
      if (idx == (CPOS) -1)
         break;
      printf("Found at position: %d\n", idx);
      idx++;
   }
 

 
Str::ReverseFind
 
CPOS ReverseFind (STRCHAR ch, CPOS startat = -1) const

 
Str::ReverseFindNoCase
 
CPOS ReverseFindNoCase (STRCHAR ch, CPOS startat = -1) const

These two methods work exactly like Find and FindNoCase, but will do a backward search. The startat parameter should identify the 0-based position at which to start looking; if the default value of -1 is passed, the scan will start at the last character of the string.

If the value returned is -1, there are no more occurrences of the character.

 

See also: Find, Replace, Compare