15

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.

ThomasWest
  • 485
  • 1
  • 7
  • 21

2 Answers2

23

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)

artm
  • 17,291
  • 6
  • 38
  • 54
3

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

Magisch
  • 7,312
  • 9
  • 36
  • 52
  • I would very much like to share some personal experiences from both company as well as azubi-side regarding your workplace question, but I can't do that on q/a. If you're interested in talking, please drop me an email. :) – simbabque Feb 08 '17 at 11:19