Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check substring exists in a string in C

Tags:

c

string

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++?

like image 849
none Avatar asked Oct 03 '22 10:10

none


People also ask

How do you find a string is a substring of another string?

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.

How do you know if a substring contains?

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.

How do I find a word in a string in c?

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.


2 Answers

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.

like image 349
nneonneo Avatar answered Oct 27 '22 11:10

nneonneo


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)
{
    ...
}
like image 37
Tango Bravo Avatar answered Oct 27 '22 09:10

Tango Bravo