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?
String comparison by using pointersscanf("%s",str1); printf("\nEnter the second string : "); scanf("%s",str2); int compare=stringcompare(str1,str2); // calling stringcompare() function.
When you need to compare two char pointers specifically, you can compare them in the usual way: by using comparison operators < , > , == etc. The issue in ths case is that you don't need to compare two char pointers. What you do need though, is to compare two C-style strings these char pointers are pointing to.
strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
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.
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