X
Write a Tutorial

Lexicographic Comparison of Strings

Submitted by careerstack

This is a function that compares two strings lexicographically without considering the case of the string so 'Bat' and 'bat' are equivalent in the comparison.

  • It returns -1 if a < b, 1 if a > b and 0 if a == b

  • a string link 'ba' will be < 'Bat'

  • tolower is a function defined in ctype.h

  int compare_fn (string a,string b)
{
    string:: iterator it1;
    string:: iterator it2;

    for(it1=a.begin(),it2=b.begin();it1!=a.end()&&it2;!=b.end();it1  ,it2  )
    {
        if(tolower(*it1) < tolower(*it2))
            return -1;
        else if(tolower(*it1) > tolower(*it2))
            return 1;
    }
    if(it1==a.end() && it2!=b.end())
        return -1;

    if(it1!=a.end() && it2==b.end())
        return 1;
    else
        return 0;
}
views: 404
Edit this Tutorial

Post Comment