C++字符串比较函数的实现(c++字符串比较大小规则)
项目中基础函数的实现其实更有意思。
公司大佬发来消息,说要我看看一个字符串比较函数的实现有没有问题,我仔细看了看,回复说没有发现问题,而且突然觉得基础函数的编写更有意思,更考基础和逻辑思维能力。
于是,决定把这个函数的实现记录下来,以后可以随时有空就看看。
话不多说,直接上代码。
#pragma once
#include <string>
#include <iostream>
using namespace std;
int compare(const string &s1, const string &s2)
{
auto first1 = s1.begin();
auto last1 = s1.end();
auto first2 = s2.begin();
auto last2 = s2.end();
for (; (first1 != last1) && (first2 != last2); ++first1, (void)++first2)
{
auto c1 = tolower(*first1);
auto c2 = tolower(*first2);
if (c1 < c2)
return -1;
else if (c2 < c1)
return 1;
}
if (first1 == last1)
{
if (first2 != last2)
return -1;
else
return 0;
}
return 1;
}
void printCompare(const string& s1, const string& s2)
{
cout << compare(s1, s2) << endl;
}