Search code examples
cstrcmp

Comparing every char in a string to a constant


Sorry, I'm relatively new to c. What I'm trying to do is loop through a string and compare each char in the string to a char. If successful, I print some value. However I'm getting a segmentation fault.

My Code:

int i;
const char* perc = '%';
char mystr[7] = "hell%o";

for(i=0;i<sizeof(mystr);i++){
        if(strcmp(mystr[i],perc)!=0){
            printf("%d",i);
        }

NOTE: I'm not using % for format strings here, I'm literally just looking for its position in the string.

Thank you.


Solution

  • strcmp() is for comparing strings. To compare characters, you can use == operator.

    Also note that sizeof is not for getting length of strings but getting number of bytes used for the type. In this case it is used for char array, so it may work according to what you want to do because sizeof(char) is defined to be 1 and therefore the number of bytes will be equal to the number of elements. Note that the terminating null-character and unused elements after that will added to the count if they exists. To get the length of string, you should use the strlen() function.

    int i;
    const char perc = '%'; /* use char, not char* */
    char mystr[7] = "hell%o";
    int len = strlen(mystr); /* use strlen() to get the length of the string */
    
    for(i=0;i<len;i++){
            if(mystr[i] != perc){ /* compare characters */
                printf("%d",i);
            }