简体   繁体   中英

rule based grammar checker

I am trying to make a simple grammar checker using c based on designing rules. If I want to design the a-an rule which search for words starting with a vowel and make sure that the identifier is 'an' not 'a'. I tried the following function:

void TheFirstRule(char string[])
{
    char *pointer;
    pointer=strstr(string,"a u");
    while(pointer!=NULL)
    {
        strncpy(pointer,"an ",3);
        pointer=strstr(string,"a u");
    }
}

this function takes a string and search for the occurrence "au" then replace it with "an ". It works correctly but the problem is: it writes 4 characters not 3 so the result is always wrong. consider this example:

input: a umbrella

output: an mbrella

any ideas how to do it correctly?

You would need an additonal buffer to do what you want - cause the length of your string is probably changing inside your function. I assumed you want to output 'an umbrella', so you replace 'au' with 'an u' to get it from the Input 'a umbrella'.

The following code works as expected:

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

void TheFirstRule(const char *input, char *output, const char* replaceText, const char* replaceWith){
  size_t pos = 0;
  while(*input != '\0'){
    if(strncmp(input, replaceText, strlen(replaceText)) == 0){
      /* text to be replaced found */
      strcpy(&output[pos], replaceWith);
      pos += strlen(replaceWith);
      input += strlen(replaceText);
    }else{
      output[pos] = *input;
      pos++;
      input++;
    }
  }
  output[pos] = '\0';
}
int main(int argc, char** argv){
  char buffer[256];
  const char text[] = { "a umbrella" };
  TheFirstRule(text, buffer, "a u", "an u");
  printf("%s\n", buffer);
  return 0;
}

Output:

an umbrella

Regardless of the length from replaceText and replaceWith you can replace substrings inside your input string and write to the output-buffer. But you have to take care, that your ouput buffer is already big enough for your string - otherwise you would get an buffer Overflow.

它可以正常工作,但是您误认为它是如何工作的,它不会写4个字符,但是会用您的String覆盖前3个字符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM