In this C++ tutorial, you will learn how to find the index of given substring in the string using string::find() function, with examples.
Find index of substring in string in C++
string::find() function returns the index of first occurrence of given substring in this string, if there is an occurrence of substring in this string. If the given substring is not present in this string, find() returns -1.
Syntax
The syntax to find the index of substring substr
in string str
is
str.find(substr)
We can also specify the starting position start
in this string and the length n
in this string, from which substring has to be searched.
str.find(substr, start, n)
start
is optional. And if start is provided, n
is optional.
Examples
1. Get Index of substring in string
In the following program, we take two strings: str
and substr
, and find the index of first occurrence of substr
in str
using string::find() function.
C++ Program
#include <iostream>
using namespace std;
int main() {
string str = "hello world. round world.";
string substr = "world";
int index = str.find(substr);
cout << "Index of substring : " << index << endl;
}
Output
Index of substring : 6
Program ended with exit code: 0
2. Index of substring in string in a specific span of the string
In the following program, we take two strings: str
and substr
, and find the index of first occurrence of substr
in str
from a specific start position in str
, using string::find() function.
C++ Program
#include <iostream>
using namespace std;
int main() {
string str = "hello world. round world.";
string substr = "world";
int start = 8;
int index = str.find(substr, start);
cout << "Index of substring : " << index << endl;
}
Output
Index of substring : 19
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to find the first occurrence of a given substring in this string using string::find() function, with examples.