C or C++. How to compare two strings given char * pointers?
Solution 1
In pretty much either one, the way is to call strcmp
. If your strings (for some weird reason) aren't NUL terminated, you should use strncmp
instead.
However, in C++ you really shouldn't be manipulating strings in char arrays if you can reasonably avoid it. Use std::string
instead.
Solution 2
I think you need to use the strcmp() function.
Solution 3
Make sure the char * isn't null, and if you want, look for the stricmp() function for case insensitive comparisons. Otherwise, use strcmp().
char * actually represents the memory address of the first character in each string. So you don't really want to be comparing the values of the pointers, but the contents they point to.
Solution 4
In C its strcmp() function as already stated. In C++ you can use the compare() function.
C:
char str1[10] = "one";
char str2[10] = "two";
if (strcmp(s, t) != 0) // if they are equal compare return 0
C++
string str1 ("one");
string str2 ("two");
if (str1.compare(str2) != 0) // if they are equal compare return 0
user69514
Updated on July 09, 2022Comments
-
user69514 almost 2 years
I am sorting my array of car two ways. one by year which is shown below. and another one by make. Make is a char* How do I compare strings when I just have pointers to them?
int i, j; for(i=0; i<100; i++){ for(j=0; j<100-i; j++){ if(carArray[i]!=NULL && carArray[j]!= NULL && carArray[j+1]!=NULL){ if(carArray[i]->year > carArray[j+1]->year){ swap(carArray[j], carArray[j+1]); } } } }
The above method works for int's (year). How can I make it work for char pointers?