Last Updated on 2021-10-22 by Clay
The string
template in C++ STL is very convenient in processing strings. To record today is how to find the specific text or substring in a string
data type variable.
The functions used in the following records are:
find()
find_first_of()
find_last_of()
find() function
The find()
function can find whether the string contains a specific text or string, and returns the index of the searched text.
The returned search result is of type size_t
, which is an unsigned integral type.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Init
string s = "Today is a nice day";
string w1 = "nice";
string w2 = "today";
// npos
printf("npos: %lu\n\n", s.npos);
// find()
// w1
size_t found1 = s.find(w1);
if (found1 != s.npos) {
printf("found word \"%s\" at: %lu\n", w1.c_str(), found1);
}
else {
printf("The word \"%s\" not found.\n", w1.c_str());
}
// w2
size_t found2 = s.find(w2);
if (found2 != s.npos) {
printf("found word \"%s\" at: %lu\n", w2.c_str(), found2);
}
else {
printf("The word \"%s\" not found.\n", w2.c_str());
}
return 0;
}
Output:
npos: 18446744073709551615
found word "nice" at: 11
The word "today" not found.
If the returned result is s.npos
(ie 18446744073709551615
), it means that the search string is not matched.
find_first_of() & find_last_of()
As the function name indicates. find_first_of()
returns the index of the first result matched, and find_last_of()
returns the index of the last matched result.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Init
string s = "Today is a nice day";
string w = "day";
// npos
printf("s: %s\n\n", s.c_str());
// find_first_of()
size_t found1 = s.find_first_of(w);
if (found1 != s.npos) {
printf("found word \"%s\" at: %lu\n", w.c_str(), found1);
}
else {
printf("The word \"%s\" not found.\n", w.c_str());
}
// find_last_of()
size_t found2 = s.find_last_of(w);
if (found2 != s.npos) {
printf("found word \"%s\" at: %lu\n", w.c_str(), found2);
}
else {
printf("The word \"%s\" not found.\n", w.c_str());
}
return 0;
}
Output:
s: Today is a nice day
found word "day" at: 2
found word "day" at: 18
References
- http://www.cplusplus.com/reference/string/string/find/
- https://stackoverflow.com/questions/2340281/check-if-a-string-contains-a-string-in-c