Verifying Substring Presence in C
The task of verifying whether a given string exists within another string arises frequently in programming. C offers a straightforward solution for this requirement.
C Function for Substring Detection
To ascertain whether a string contains a substring, C provides the std::string::find function. It accepts a substring as an argument and returns a position indicator.
Code Implementation
The code snippet provided below demonstrates the usage of std::string::find:
std::string s1 = "Hello, world!"; std::string s2 = "world"; if (s1.find(s2) != std::string::npos) { std::cout << "found!" << '\n'; }
In this example, if s2 is a substring of s1, the message "found!" will be displayed because std::string::find returns a value other than std::string::npos, which indicates the absence of the substring.
Note: Considerations
Keep in mind that the function assumes both s1 and s2 are of type std::string. Additionally, the function determines whether s2 appears exactly as it is within s1, without any character variations or additional spaces.
The above is the detailed content of How Can I Efficiently Check for Substring Existence in C ?. For more information, please follow other related articles on the PHP Chinese website!