用strcmp()比较字符串

时间:2014-06-25 06:02:09

标签: c++ string compare strcmp

代码是:

#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语句块? strcmp中使用什么方法来比较这些字符串?它是由总数,字节对,无论是什么字符?

1 个答案:

答案 0 :(得分:3)

首先&#39; J&#39;与J&#39;相比,他们是平等的。然后&#39;我&#39;被比作&#39; a&#39;, &#39;我&#39; &GT; &#39;一个&#39;

因此,

Jill is greater than Jacko