简体   繁体   中英

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.

Total two scenarios are possible:-

  1. if we have the length of b > 0 , then we have to make sure that a[i] ASCI I 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM