Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C or C++. How to compare two strings given char * pointers?

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?

like image 229
user69514 Avatar asked Feb 24 '10 23:02

user69514


People also ask

How do you compare two strings using pointers?

String comparison by using pointersscanf("%s",str1); printf("\nEnter the second string : "); scanf("%s",str2); int compare=stringcompare(str1,str2); // calling stringcompare() function.

How do I compare char pointers?

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.

Can you compare a string and a character in C?

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.

Can I use == to compare two strings?

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.


1 Answers

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.

like image 95
T.E.D. Avatar answered Sep 18 '22 16:09

T.E.D.