用strcmp()比较字符串

Comparing strings with strcmp()

本文关键字:比较 字符串 strcmp      更新时间:2023-10-16

代码为:

#include <iostream>
int main() {
const char *str1{"Jill"};
const char *str2{"Jacko"};
int result{std::strcmp(str1, str2)};
if(result < 0) {
std::cout << str1 << " is less than " << str2 << '.' << std::endl;
} else if(result == 0) {
std::cout << str1 << " is equal to " << str2 << '.' << std::endl;
} else {
std::cout << str1 << " is greater than " << str2 << '.' << std::endl;
} 
return 0;
}

输出:Jill大于Jacko。

我的新手问题是:为什么它返回else语句块来确认Jill大于Jacko?strcmp中使用什么方法来比较这些字符串?是按总字节数,还是按字符数?

首先比较'J'和'J',它们是相等的。然后将i与a进行比较,'i'> 'a'>

因此,

Jill is greater than Jacko