Reputation: 27
I need to compare the elements of a string. I have tried to run the following code but this not work. Any idea how to access element of the string and compare against alphabets ?
char* my_string = "Excellent";
if ( strcmp (my_string[0], "D") )
{
printf("\n\rThe First Element is D: \n\r");
}
if ( strcmp (my_string[0], "E") )
{
printf("\n\rThe First Element is E: \n\r");
}
Upvotes: 2
Views: 808
Reputation: 106096
my_string[0]
is a char
and should be compared to 'D'
(another char) with ==
, not compared to "D" (a string literal) with strcmp
, which is only suitable for ASCIIZ (nul-terminated) strings.
Separately, you should (and in C++ at least must) use const char* my_string = "Excellent";
, indicating that you can't change the text my_string
points to (most compilers will put it in read-only memory, and even if they don't you shouldn't change it as the compiler's entitled to assume it won't ever be changed.).
Upvotes: 3
Reputation: 316
What you are doing is comparing the char(my_string[0]) to the string("D") which is unacceptable by strcmp(char *arg1, char *arg2)
. You can compare the characters by using '==', '>' and '<' operators like
if( my_string[0] == 'E' )
printf("\n\rThe First Element is E: \n\r");
Upvotes: 1