Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find vs find_first_of when searching for empty string

Tags:

c++

string

stl

In STL, when I do s.find(""), it returns 0 while s.find_first_of("") returns -1 (npos). What is the reason for this difference?

like image 951
Ravi Sankar Raju Avatar asked Apr 02 '15 23:04

Ravi Sankar Raju


People also ask

What is the difference between find and find_ first_ of?

The difference is that while find searches for one particular value, find_first_of searches for any of several values. Specifically, find_first_of searches for the first occurrence in the range [first1, last1) of any of the elements in [first2, last2) .

What does string find return if not found?

In this tutorial, we will learn about the Python String find() method with the help of examples. The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.

What does Find_first_of return?

The C++ function std::algorithm::find_first_of() returns an iterator to the first element in the range of (first1,last1) that matches any of the elements in first2,last2. If no such element is found, the function returns last1.

How do you find first occurrence of a character in a string C++?

string find in C++ String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0.


1 Answers

s.find(t) finds the first occurrence of the substring t in s. If t is empty, then that occurrence is at the beginning of s, and s.find(t) will return 0.

s.find_first_of(t) finds the first occurrence of one of the characters in t. If t is the empty string, then there are no characters in t, so no occurrence can be found, and find_first_of will return npos.

Live on ideone.

like image 51
rici Avatar answered Oct 13 '22 13:10

rici