'How to compare more than 2 strings in C?
I know there is the strcmp but it just let me compare two strings, And I need to compare a lot of them
This one doesn't work:
if(strcmp (resposta, "S" || "s" || "N" || "n")== 0)
printf("Resposta = S");
else
printf("Resposta != S");
printf("\nfim");
Solution 1:[1]
Your method isn't working as you expected because the expression "S" || "s" || "N" || "n"
is the same as "S"
because of short circuit.
You have to compare it with the candidate strings one by one:
if (strcmp(resposta, "S") == 0
|| strcmp(resposta, "s") == 0
|| strcmp(resposta, "N") == 0
|| strcmp(resposta, "n") == 0)
{
printf("Resposta = S");
}
Solution 2:[2]
if( strcmp (resposta, "S") == 0 || strcmp (resposta,"s") == 0 || strcmp (resposta,"N") == 0 || strcmp (resposta, "n") == 0)
Solution 3:[3]
The signature of the standard library function strcmp
is -
int strcmp(const char *s1, const char *s2);
However, you are calling it as
strcmp(resposta, "S" || "s" || "N" || "n")
The second argument evaluates to 1, which is of type int
, because the string literals evaluate to a pointer to its first character and it cannot be NULL
. This is clearly wrong.
You should replace it by
if(!((strcmp(resposta, "S") && strcmp(resposta, "N") && strcmp(resposta, "n")))
printf("Resposta = S");
else
printf("Resposta != S");
Solution 4:[4]
If you have a lot of strings to compare against, you could make an array out of them and iterate over it. In this example the array is terminated with a NULL
(so the while
condition works):
const char *strings[] = { "S", "Sim", "N", "NAO", NULL };
// ^ add more strings here
const char **s = strings;
while (*s) {
if (strcmp(resposta, *s) == 0) {
(void) printf("Matched: %s\n", *s);
break; // stop searching when a match is found (the matching string is *s)
}
++s;
}
if (!*s) {
(void) printf("Didn't match anything\n");
}
A better way if you have a lot of strings to match against would be to sort the array of strings and do binary search in it.
Solution 5:[5]
If you're looking for a string that is only a single char
, you can use a switch
statement.
switch(*string) //will compare the first character of your string
{
case('s'):
{
//whatever you do
break;
}
case('S'):
{
//whatever else
break;
}
... //other characters
default:
{
//error handling on incorrect input
break;
}
}
Edit: If you are comparing strings of different length (i.e. you are looking for a prefix in a string), be aware that strcmp()
will never consider them equal.
If you need to find a prefix, you need to strncmp()
(note the n) with each string and string length individually.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CennoxX |
Solution 2 | bitfiddler |
Solution 3 | ajay |
Solution 4 | Arkku |
Solution 5 |