Text and Parsing Utilities
Find Substring
std::string::find locates the first position where a smaller piece of text appears.
Find Substring
find_substring.cpp
#include <iostream>
#include <string>
int main() {
std::string needle = ;
std::string line = "app.log: ready";
std::size_t found = line.find(needle);
int position = found == std::string::npos ? -1 : static_cast<int>(found);
std::cout << "needle=" << needle << std::endl;
std::cout << "position=" << position << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string needle = ;
std::string line = "app.log: ready";
std::size_t found = line.find(needle);
int position = found == std::string::npos ? -1 : static_cast<int>(found);
std::cout << "needle=" << needle << std::endl;
std::cout << "position=" << position << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string needle = ;
std::string line = "app.log: ready";
std::size_t found = line.find(needle);
int position = found == std::string::npos ? -1 : static_cast<int>(found);
std::cout << "needle=" << needle << std::endl;
std::cout << "position=" << position << std::endl;
return 0;
}
find
`find` returns the first matching position, or `std::string::npos` when the text is not present.
position
String positions are zero-based indexes.