C++如何实现python中的startswith和endswith
#include<iostream>
#include <string>
using namespace std;
void AdjustIndices(int& start, int& end, std::string::size_type len)
{
len = (int)len;
if (end > len)
end = len;
else if (end < 0)
{
end += len;
if (end < 0)
end = 0;
}
if (start < 0)
{
start += len;
if (start < 0)
start = 0;
}
}
int _string_tailmatch(const std::string& self, const std::string& substr, int start, int end, int direction)
{
int selflen = (int)self.size();
int slen = (int)substr.size();
const char* str = self.c_str();
const char* sub = substr.c_str();
AdjustIndices(start, end, selflen);
if (direction < 0)
{
if (start + slen > selflen)
return 0;
}
else
{
if (end - start<slen || start>selflen)
return 0;
if (end - slen > start)
start = end - slen;
}
if (end - start >= slen)
return !std::memcmp(str + start, sub, slen);
return 0;
}
bool endswith(const std::string& str, const std::string& suffix, int start = 0, int end = 2147483647)
{
int result = _string_tailmatch(str, suffix, start, end, +1);
return static_cast<bool>(result);
}
bool startswith(const std::string& str, const std::string& suffix, int start = 0, int end = 2147483647)
{
int result = _string_tailmatch(str, suffix, start, end, -1);
return static_cast<bool>(result);
}
int main()
{
string a = "djaskdjasd";
bool result = startswith(a, "da");
cout << "result:" << result << endl;
bool result1 = startswith(a, "dj");
cout << "result1:" << result1 << endl;
bool result2 = endswith(a, "da");
cout << "result2:" << result2 << endl;
bool result3 = endswith(a, "sd");
cout << "result3:" << result3 << endl;
return 0;
}
- 运行结果如下