[英]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. 在字符串a的长度大于字符串b的长度并且字符串a以字符串b开头的情况下,我很有趣。
Example: 例:
string a="abcdefghi" 字符串a =“ abcdefghi”
string b="abcde" 字符串b =“ abcde”
The function will return 0. I want to know if there is any chance for this function to return 1; 该函数将返回0。我想知道此函数是否有返回1的机会; in this conditions. 在这种情况下。
Total two scenarios are possible:- 共有两种情况:
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.. 如果我们的长度b > 0
,则必须确保a[i] ASCI
I值必须小于b[i]
ASCII值。
string a="abcdefghi" string b="abcde"
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
]. 在您的示例中,当我们到达索引5
,结果将是不确定的,这意味着b[5]
可能包含其ASCII值大于a[i
]的垃圾值。 or the result might be vise-versa. 否则结果可能相反。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.