• C

finding specific char substring

I need a function to search for specific text in a string.

I tried:  
if (instr(line, "hello") != 0 )    /* line is a string of type char */

but I keep getting an unresolved error at compile.

If I am doing something wrong with this function...please let me know.

If you could also provide other means of doing this it would be much appreciated.

Thanks

 
siggyjavAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
jkrConnect With a Mentor Commented:
Use 'strstr()' instead:

#include <string.h>

if (strstr(line, "hello") != 0 )    /* line is a string of type char */

Alittle more complex example would be

/* STRSTR.C */

#include <string.h>
#include <stdio.h>

char str[] =    "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] =   "         1         2         3         4         5";
char fmt2[] =   "12345678901234567890123456789012345678901234567890";

void main( void )
{
   char *pdest;
   int  result;
   printf( "String to be searched:\n\t%s\n", string );
   printf( "\t%s\n\t%s\n\n", fmt1, fmt2 );
   pdest = strstr( string, str );
   result = pdest - string + 1;
   if( pdest != NULL )
      printf( "%s found at position %d\n\n", str, result );
   else
      printf( "%s not found\n", str );
}


Output

String to be searched:
   The quick brown dog jumps over the lazy fox
            1         2         3         4         5
   12345678901234567890123456789012345678901234567890

lazy found at position 36

0
 
van_dyCommented:
consider the following function:

#include <string.h>
#include <stdio.h>

int getindex(line, string)
      char *line;
      char *mystring;
{
      int i;
      int slen = strlen(mystring);
      int llen = strlen(line);

      for(i = 0; i < llen; i++){
            if(!strncmp(line + i, mystring, slen))
                  return i;
      }

      return -1;
}

int main()
{
      char *line = "My name is XYZ";
      char *string = "XYZ";
      printf("%d\n", getindex(line, string));
      return 0;
}

getindex returns the index in the line string, where the string mystring appears first.

hope this helps,
van_dy
0
 
van_dyCommented:
the documentation for instr() tells its a curses function, used for extracting string of characters
starting from the current cursor position in a named window. i think you are using the wrong
function, the resolve error comes because you arent linking in the curses library.
0
 
van_dyCommented:
errata:

int the definition of getindex we should have ..

int getindex(line, mystring);  //mistakenly typed string earlier
           char *line;
            char *mystring;
{
 ......
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.