0
How to find a string in a 2D array of char in C
Given the two dimensional array of characters in C: char arr[5][3]={"11","22","33","44","55"}; how do you find the index of "22" in the given array? This loop doesn't seem to work: int i = 0; char ch[3] = "22"; while(i < 5){ if(arr[i] == ch){printf("Index of \"22\" = %d",i); break;} i++; }
2 Answers
+ 1
You cannot use == to compare 2 strings in C. That basically compares their addresses since a string is a char array. In <string.h>, there is strcmp(char*, char*), Which compares 2 strings and return 0 if they are equivalent.
In a nutshell, include <string.h> and use
!strcmp(arr[i], ch).
0
Thanks!