简体   繁体   中英

c - compare letters in a string

Ok, this must be easy but I'm having one of those days :-p

I have an char* array which for example purposes is as follows:

char* symbols [] = {"++-", "--+"};

I'm trying to loop over symbols[0] and symbols[1] and compare each of the chars to see if its a + or a -

I'm trying:

char* tmp = symbols[0];
for (int i = 0; i < strlen(tmp); i++)
{
    if(strcmp(tmp[i], "+") == 0)
    {
         printf("It's a plus!\n");
    }
    else if (strcmp(tmp[i], "-") == 0)
    {
         printf("Its a minus!\n");
    }
}

However, when compiling I'm getting a warning:

comparison between pointer and integer [enabled by default]

I assume I'm missing something basic - can anyone help me see the wood from the trees?

symbols is of type pointer to char . You need an array of pointers to char .
Change

char* symbols = {"++-", "--+"};  

to

char* symbols[] = {"++-", "--+"};  

and condition in if

if(strcmp(tmp[i], "+") == 0)  

to

if(tmp[i] == '+')

" " and ' ' are not the same. Use single quotes to represent a character, otherwise it's an array of characters (which is an array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM