How to compare part of strings in C?

1

I only know how to compare two strings in C, but can I compare only part of a string? I wanted to develop a program that reads snippets of a complaint and based on those snippets give a suggested answer. Is it possible to read only snippets in C? In Java I know it's possible, but I'd like to do it in C. Thanks.

    
asked by anonymous 17.05.2018 / 12:11

2 answers

1

You can use the strcasestr() function of the default library string.h to check (regardless of whether uppercase or lowercase) if one string is contained in another, eg

#define _GNU_SOURCE

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

char reclamacao[] = "Gostaria de saber horarios entre Rio de Janeiro x Aparecida";

int main( void )
{
    if( strcasestr( reclamacao, "saber horarios" ) )
    {
        printf("Para visualizar horários entre no site...\n");
    }
    else
    {
        printf("Não Encontrei!\n");
    }

    return 0;
}
    
17.05.2018 / 14:01
0

Yes, it is possible.

You will need to use the memcmp function.

Example:

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

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n = memcmp (buffer1, buffer2, sizeof(buffer1));

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}

See the function manual for more details.

    
17.05.2018 / 12:22