How do I find the index of a character within a string in C?

前端 未结 5 1211
野的像风
野的像风 2021-01-31 15:12

Suppose I have a string \"qwerty\" and I wish to find the index position of the e character in it. (In this case the index would be 2)

5条回答
  •  梦毁少年i
    2021-01-31 15:38

    void myFunc(char* str, char c)
    {
        char* ptr;
        int index;
    
        ptr = strchr(str, c);
        if (ptr == NULL)
        {
            printf("Character not found\n");
            return;
        }
    
        index = ptr - str;
    
        printf("The index is %d\n", index);
        ASSERT(str[index] == c);  // Verify that the character at index is the one we want.
    }
    

    This code is currently untested, but it demonstrates the proper concept.

提交回复
热议问题