Search code examples
c++string-matching

C++ comparing 2 strings


I have the following code:

int compare(string a,string b)
{
    int length=a.length();
    for(int i=0; i < length; i++)
    {
        if(a[i]<b[i])
            return 1;
        if(a[i]>b[i])
            return 0;
    }
    ....
}

I'm interesting in the cases when length of string a is bigger than length of string b and string a starts with string b.
Example:
string a="abcdefghi"
string b="abcde"
The function will return 0. I want to know if there is any chance for this function to return 1; in this conditions.


Solution

  • Total two scenarios are possible:-

    1. if we have the length of b > 0 , then we have to make sure that a[i] ASCII value must be less than b[i] ASCII value..

      string a="abcdefghi"
      string b="abcde"
      
    2. In your example when we reach at index 5, the result would be undefined, means b[5] might contain garbage value whose ASCII value is greater than a[i]. or the result might be vise-versa.