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

前端 未结 5 1216
野的像风
野的像风 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条回答
  •  难免孤独
    2021-01-31 15:32

    This should do it:

    //Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
    int get_index(char* string, char c) {
        char *e = strchr(string, c);
        if (e == NULL) {
            return -1;
        }
        return (int)(e - string);
    }
    

提交回复
热议问题