comment comparer deux chaînes dans C? Aidez-moi, je suis débutant @@Comment comparer un pointeur à une chaîne dans C
char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
comment comparer deux chaînes dans C? Aidez-moi, je suis débutant @@Comment comparer un pointeur à une chaîne dans C
char *str1 = "hello";
char *str2 = "world";
//compare str1 and str2 ?
Vous pouvez utiliser strcmp
:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int v;
const char *str1 = "hello";
const char *str2 = "world";
v = strcmp(str1, str2);
if (v < 0)
printf("'%s' is less than '%s'.\n", str1, str2);
else if (v == 0)
printf("'%s' equals '%s'.\n", str1, str2);
else if (v > 0)
printf("'%s' is greater than '%s'.\n", str1, str2);
return 0;
}
Résultat:
'hello' is less than 'world'.
+1, mais je ne lierais pas à cette page, il utilise l'horrible obsolète 'gets' fonction dans son exemple, ce qui n'est certainement pas une bonne idée pour quelqu'un commençant C. La page [POSIX] (http: // www .opengroup.org/onlinepubs/000095399/functions/strcmp.html) est une alternative. – dreamlax
@dreamlax: D'accord :) Fixe ... –
if (strcmp(str1, str2) == 0)
same
Vous pouvez comparer deux char*
s en utilisant la strcmp
function.
Celles-ci devraient être 'const char *'. – dreamlax