Prathamesh
Prathamesh

Reputation: 23

Way to compare unequal array or string in c++

I am working on a problem in with two string are taken as input and we have to see if the first char is same as first char of other string and trigger a case! so when i compare them using for or while loop one of the two goes out of limit and returns wrong result!

i tried finding many ways to solve this, but can't find a good one!

Upvotes: 2

Views: 232

Answers (2)

Raj Singh
Raj Singh

Reputation: 1

I have written a code which prints -1 in case the first string is either lexicographically smaller than the second one, or has smaller size as compared to the second one. It prints 1 in case first string is either lexicographically greater than the second one, or has larger size as compared to the second one. It prints 0 if both are same.

Note: Please test code fully. Did not test it as well as I would have liked!.

Code is available at following URL:

int main(){
    string first = "adsc", second = "abc";
    int i = 0, ans = 0; 
    while(true){
        if(i == first.size() or i == second.size() or ans != 0)
            break;
        if(first[i] < second[i])
            ans = -1;
        else if(first[i] > second[i])
            ans = 1;
        i++;
        }
        if(ans == 0 and first.size() < second.size())
            ans = -1;
        else if(ans == 0 and first.size() > second.size())
            ans = 1;
    cout<<ans;
}

https://ideone.com/XZymc6

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

If you mean c-strings then use the standard C function strcmp.

Otherwise if character arrays do not contain strings but their lengths of the actual data are known then at first you can compare the lengths and if they are equal then you can use the standard C function memcmp.

If you are using objects of the type std::string then there are defined comparison operators for the type.

For other containers and arrays you can use the standard algorithm std::lexicographical_compare.

Upvotes: 3

Related Questions