Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare 2 Character Arrays [duplicate]

Tags:

c

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.

like image 220
ThomasWest Avatar asked Nov 15 '16 08:11

ThomasWest


2 Answers

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)

like image 127
artm Avatar answered Oct 24 '22 10:10

artm


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

like image 23
Magisch Avatar answered Oct 24 '22 10:10

Magisch