How do I compare these two character arrays to make sure they are identical?
char test[10] = "idrinkcoke"
char test2[10] = "idrinknote"
I'm thinking of using for loop
, but I read somewhere else that I couldnt do test[i] == test2[i]
in C.
I would really appreciate if someone could help this. Thank you.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With