Home > Software design >  how can you compare two strings punctuation insensitively?
how can you compare two strings punctuation insensitively?

Time:11-14

I am busy making a spell checker and when I compare the word I'm to the dictionary version im it returns false. I used strcasecmp to compare them case insensitively but the apostrophe is still a problem. How can I compare the two (punctuation insensitively) and get true as the output?

CodePudding user response:

Write your own routine to skip punctuation:

#include <stdio.h>
#include <ctype.h>

int insenistive_strcmp(char const* s1, char const* s2)
{
    unsigned char const* p1 = (unsigned char const*)s1;
    unsigned char const* p2 = (unsigned char const*)s2;

    for (;;   p1,   p2)
    {
        while (ispunct(*p1))
              p1;

        while (ispunct(*p2))
              p2;
        
        int ch1 = toupper(*p1);
        int ch2 = toupper(*p2);

        if (!ch1 || !ch2 || ch1 != ch2)
            return ch1 - ch2;
    }
}

int main()
{
    printf("%d\n", insenistive_strcmp("I'm", "im"));
}
  • Related