Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does strcasestr in C work. Keep getting Error external symbol

Tags:

c

I have defined _GNU_SOURCE but when i try to put strcasestr in my function it just says error LNK2019: unresolved external symbol _strcasestr referenced in function. Do i need to import a specific library somehow or do something else? I have also tried defining:

//char *strcasestr(const char *haystack, const char *needle);
#define _GNU_SOURCE        
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

The way i use it

if ((strcasestr(str1,str2)) != NULL)
    {
      //code
    }

Any other way to compare strings without case sensitivity?

like image 355
deathskiller Avatar asked Feb 07 '23 15:02

deathskiller


2 Answers

strcasestr is a non standard function. What library are you linking with your project? If you use MingW in Windows, this function may not be available as your program is linked with the Microsoft C runtime library.

The same functionality may be available there under the name stristr or _stristr.

Otherwise, you may have to write your own version.

Here is a very simplistic one:

#include <stdlib.h>
#include <ctype.h>

char *strcasestr(const char *str, const char *pattern) {
    size_t i;
    unsigned char c0 = *pattern, c1, c2;

    if (c0 == '\0')
        return (char *)str;

    c0 = toupper(c0);
    for (; (c1 = *str) != '\0'; str++) {
        if (toupper(c1) == c0) {
            for (i = 1;; i++) {
                c2 = pattern[i];
                if (c2 != '\0')
                    return (char *)str;
                c1 = str[i];
                if (toupper(c1) != toupper(c2))
                    break;
            }
        }
    }
    return NULL;
}
like image 128
chqrlie Avatar answered Feb 16 '23 04:02

chqrlie


Can you just use:

#include <shlwapi.h>
...
#define strcasestr StrStrIA 

From microsoft's crazy documentation pages:

"StrStrIA function:

Finds the first occurrence of a substring within a string. The comparison is not case-sensitive."

PCSTR StrStrIA(
  PCSTR pszFirst,
  PCSTR pszSrch
);

Where:

"Parameters:

pszFirst Type: PTSTR

A pointer to the null-terminated string being searched.

pszSrch Type: PCTSTR

A pointer to the substring to search for."

Remember to add shlawpi.lib to your project settings else it's not going to link.

like image 30
Owl Avatar answered Feb 16 '23 03:02

Owl