How to properly find the matching character in another string

i would like to know the best way to compare a single character of a string to another whole string and find the matching character so to say. The probably most important snippets of my code are the user input request:
string text = get_string("text: ");
and my predefined "comparison"-string= char lowerabc[] = "abcdefghijklmnopqrstuvwxyz";
Now, i would like to take the n-th value of the text and find the matching character in lowerabc.
My first try was to use a for-loop and set the end-criteria to when their values match, smth like this: for(int j=0;text[i] == lowerabc[j] ; j++){}
but as i’ve found out this compares the address of both and therefore makes no sense. Therefore i stumbled upon the strcmp() function and edited the code to match the zero-value as the end criteria: for(int j=0;strcmp(text[i], lowerabc[j])==0 ; j++){} but once i compile it, it throws me the error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion] Im sorry, but it really seems like that im too stubborn to make out the difference in nature of these two variables so that it would say smth like that to me. So therefore i would like to ask what would be the most efficient way to do this type of comparison. Ty all very much for your help

>Solution :

You can use strchr() to find single character from a string.

#include <stdio.h>
#include <string.h>

/* mock */
typedef char* string;
string get_string(const char* x) {
    static char ret[] = "hoge123abc";
    return ret;
}

int main(void) {
    string text = get_string("text:  ");
    char lowerabc[] = "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; text[i] != '\0'; i++) {
        char* res = strchr(lowerabc, text[i]);
        if (res != NULL) {
            int idx = res - lowerabc;
            printf("%c is found at lowerabc[%d]\n", text[i], idx);
        } else {
            printf("%c is not found in lowerabc\n", text[i]);
        }
    }
    return 0;
}

output:

h is found at lowerabc[7]
o is found at lowerabc[14]
g is found at lowerabc[6]
e is found at lowerabc[4]
1 is not found in lowerabc
2 is not found in lowerabc
3 is not found in lowerabc
a is found at lowerabc[0]
b is found at lowerabc[1]
c is found at lowerabc[2]

Leave a Reply