hkvega
hkvega

Reputation: 315

Find the text starting with another text

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

Answers (5)

0xCAFEBABE
0xCAFEBABE

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

user870774
user870774

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

Bastardo
Bastardo

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

patapizza
patapizza

Reputation: 2398

if (strstr(text, textneedtoSearch) != NULL)
  printf("found\n");

Upvotes: 3

Related Questions