How to compare part of strings in C?

Asked

Viewed 1,119 times

1

I can only compare two strings in full in C, but can I compare only part of a string? I wanted to develop a program that reads excerpts from a complaint and based on these excerpts give a response suggestion. Is it possible to read only excerpts in C? In Java I know it is possible, but I would like to do in C. Thank you.

  • Compare only one part ? What do you mean ? Know if one string contains another ? I suggest you make your question clearer by adding examples of the results you’d expect to see between some comparisons

  • Come on. Let’s assume that the variable "complaint" receives the text: "I would like to know schedules between Rio de Janeiro x Aparecida". I’d like to do something like that. If in the "complaint" variable contains the string "know times" return to String "To view times sign in to the site..."

2 answers

1

You can use the function strcasestr() of the standard library string.h to check (not considering uppercase or lowercase letters) if a string is contained in another, for example:

#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;
}
  • Great friend, this is exactly what I would like. check if one string is contained in another. Thank you very much.

  • Error in line if( strcasestr( complaint, "know times" ) ). Error is "[Error] 'strcasestr' was not declared in this Scope"

  • @Ericknascimento: Corrected by :)

0

Yes, it is possible.

You will need to use the function memcmp.

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.