Is there a function in c that will return the index of a char in a char array?

后端 未结 6 1631
难免孤独
难免孤独 2021-01-01 14:20

Is there a function in c that will return the index of a char in a char array?

For example something like:

char values[] = \"0123456789ABCDEFGHIJKLMN         


        
6条回答
  •  生来不讨喜
    2021-01-01 14:48

    Safe index_of() function that works even when it finds nothing (returns -1 in such case).

    #include 
    #include 
    ptrdiff_t index_of(const char *string, char search) {
        const char *moved_string = strchr(string, search);
        /* If not null, return the difference. */
        if (moved_string) {
            return moved_string - string;
        }
        /* Character not found. */
        return -1;
    }
    

提交回复
热议问题