Search code examples
cstringpointersstrcmp

How to create a "X" terminated string in C?


I'm trying to create a counter that counts the amount of characters in a string before "?". I have issues with using strcmp to terminate the while-loop and end up with a segmentation fault. Here's what I have:

void printAmount(const char *s)
{
    int i = 0;
    while ( strcmp(&s[i], "?") != 0 ) {
        i++;
    }
    printf("%i", i);
}

Solution

  • Don't use strcmp for this. Just use the subscript operator on s directly.

    Example:

    #include <stdio.h>
    
    void printAmount(const char *s) {
        int i = 0;
        while (s[i] != '?' && s[i] != '\0') {
            i++;
        }
        printf("%d", i);
    }
    
    int main() {
        printAmount("Hello?world"); // prints 5
    }
    

    Or use strchr

    #include <string.h>
    
    void printAmount(const char *s) {
        char *f = strchr(s, '?');
        if (f) {
            printf("%td", f - s);
        }
    }