Reputation: 315
Is there any method in C
can find a text within another text?
For example, text = "abaHello"
, textneedtoSearch = "Hello";
.
If the text
contains "Hello"
, return true, else return false
.
Upvotes: 9
Views: 263
Reputation: 5666
The C
function strstr
returns a pointer to the start of the word you were looking for if it is contained in the text you were searching in, or NULL
, if it does not contain the word you are looking for.
Syntax:
char *p = strstr(wheretolook,whattolookfor);
Upvotes: 3
Reputation:
You can find a text on string file:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *fp=fopen(argv[1],"r");
char tmp[256]={0x0};
while(fp!=NULL && fgets(tmp, sizeof(tmp),fp)!=NULL)
{
if (strstr(tmp, argv[2]))
printf("%s", tmp);
}
if(fp!=NULL) fclose(fp);
return 0;
}
Upvotes: 3
Reputation: 11358
Use strstr
, see http://pubs.opengroup.org/onlinepubs/9699919799/functions/strstr.html
Upvotes: 10
Reputation: 4152
Character and string searching functions
`char *strstr( const char *s1, const char *s2)`
returns a pointer to the first instance of string s2 in s1. Returns a NULL pointer if s2 is not encountered in s1.
In additon,
int strcmp(const char *s1, const char *s2);
strcmp
compares the string s1 to the string s2. The function returns 0 if they are the same, a number < 0 if s1 < s2, a number > 0 if s1 > s2.This is one of the most commonly used of the string-handling functions.
And check this link for anything about string functions in C, C string functions
Upvotes: 6