0

I need get position of word in text, but I can't convert a pointer with char *text to char text[] to compare each character.

I am trying to find the location of the first substring in a text that matches a particular word.

#include <stdio.h>
#include <string.h>
int searchWord(char *word, char *text);

int main (int argc, char *argv[])
{
    int i,searchString;
    if (!(argc>2)) {
        printf("Need 2 args");
        return 0;
    }
    printf("aaa %d\n" ,searchWord(argv[1],argv[2]));

    return 0;
}

int searchWord(char *word, char *text) // I need use that function to search.
{
    printf("\n\n%s\n\n",&word[0]);
    return 0;
}
Bruno Novais
  • 29
  • 3
  • 10
  • Compile with all warnings and debug info (`gcc -Wall -Wextra -g`). End every `printf` format string with `\n` or call `fflush`. Use the debugger `gdb` – Basile Starynkevitch Jan 28 '15 at 06:10

2 Answers2

1

It is not a problem with char* and char[] conversion, it is a problem with converting char* to int since argv[] is an array of an array of character.

Try this -- it uses pointer arithmetic and probably work:

int SearchWord( char *word, char *text, unsigned int length ) {
  unsigned int i = 0, d = 0, x = 0;
  x = strlen( text );
  // Keep looping til we reach less than total length
  for (; i <= ( x - length ); i++) {
    if (strncmp( text, word, length ) == 0) {
      d = i;
      break;
    }
    else {
      // Moving 1 character position
      text++;
    }
  }
  // Check if no match was found
  if (i == (x - length) {
    return -1;
  }
  for (i = 0; i <= d; i++) {
    // Revert the text
    text--;
  }
  return d;
}
1

Assuming that text is composed of words separated by spaces, you can consider tokenizing text, and then iterating through the tokens to see if they match word. Try making use of strtok(), and there is a lot of documentation online for how to use the function.

I found a relevant question on how to use strtok here: how to use strtok.

You can try to find the position this way:

int search(char * word, char * text, unsigned int length) {
    char * token = strtok(text, " ");
    int position = 0;

    while (token != NULL) {
        // if word matches the token, we found our word
        if (! strncmp(word, token, length)) {
            return position;
        } else {
            position += (strlen(token) + 1);
            // get the next token from the text
            token = strtok(NULL, " ");
        }
    }
    // didn't find it
    return -1;
}
Community
  • 1
  • 1
rabbit
  • 1,476
  • 12
  • 16