How to Compare 2 Character Arrays

You can use the C library function strcmp

Like this:

if strcmp(test, test2) == 0

From the documentation on strcmp:

Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.

and on the return value:

returns 0 if the contents of both strings are equal


but I read somewhere else that I couldnt do test[i] == test2[i] in C.

That would be really painful to compare character-by-character like that. As you want to compare two character arrays (strings) here, you should use strcmp instead:

if( strcmp(test, test2) == 0)
{
    printf("equal");
}

Edit:

  • There is no need to specify the size when you initialise the character arrays. This would be better:

    char test[] = "idrinkcoke";
    char test2[] = "idrinknote";

  • It'd also be better if you use strncmp - which is safer in general (if a character array happens to be NOT NULL-terminated).

    if(strncmp(test, test2, sizeof(test)) == 0)

Tags:

C