I'm trying to check whether a string contains a substring in C like:
char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
What is something to use instead of string::find
in C++?
Simple Approach: The idea is to run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop running another loop checking for sub-string from every index.
Java String contains() method It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement. The contains() method in Java returns true only if this string contains “s” else false.
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
if (strstr(sent, word) != NULL) {
/* ... */
}
Note that strstr
returns a pointer to the start of the word in sent
if the word word
is found.
Use strstr
for this.
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
So, you'd write it like..
char *sent = "this is my sample example";
char *word = "sample";
char *pch = strstr(sent, word);
if(pch)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With