0

*** C newbie here. ***

My program has an array that holds an HTML document (one array cell per HTML character). I have a while-loop which loops over each cell of the array. At each array cell I check to see if the cell value is the start of a certain string; for example, does the current cell contain '&' and the next cell contain 'n' and the next 'b' and then 's' and then 'p' and then ';' (i.e., " ").

I wrote a function to do the comparison. See below. Does C already have a function which does this comparison? If not, is the function that I show below how a C expert would write it? If no, how would a C expert write the function?

// p points to a cell in an array
// s is a string
// This function answers the question: does p start with s?
int cmpString(char *p, char *s) {
    char *q = p;  // Don't modify the position of the array pointer so make a copy
    
    while (*s != 0) {
       if (tolower(*q) != tolower(*s))
          return 0; 
       q++;
       s++;
    }
    return 1; 
}
Roger Costello
  • 3,007
  • 1
  • 22
  • 43
  • https://stackoverflow.com/questions/12784766/check-substring-exists-in-a-string-in-c – OldProgrammer Jan 27 '21 at 20:26
  • Also check https://stackoverflow.com/questions/4770985/how-to-check-if-a-string-starts-with-another-string-in-c in case you still want your `cmpString` – naicolas Jan 27 '21 at 20:29
  • Are you looking for [`strstr()`](https://linux.die.net/man/3/strstr)? – John Bollinger Jan 27 '21 at 20:31
  • Note that an experienced programmer would not approach the task with substring searching in the first place. With a structured data format such as HTML, it is tricky and dangerous to attempt to work directly on raw data in string form. One almost always wants to *parse* the data in a way that is appropriate to the data format. – John Bollinger Jan 27 '21 at 20:38
  • My understanding is that strstr() would search the entire array, looking for the first occurrence of the string. That's not what I want. I want this: given the cell that I am currently positioned at, does it plus the next 5 cells contain " " – Roger Costello Jan 27 '21 at 20:56

0 Answers0