C++如何实现python中的startswith和endswith

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;
    //如果end超出字符串长度
    if (end > len)
        end = len; //则以字符串长度为准
    else if (end < 0)
    {//如果end为负数
        end += len; //则先加上字符串长度
        if (end < 0)//如果还是为负数
            end = 0;//则为0
    }
    //如果start为负数
    if (start < 0)
    {
        //则加上字符串长度,注意不是以0校准
        start += len;
        if (start < 0)//如果还是负数
            start = 0;//才以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);

    //字符串头部匹配(即startswith)
    if (direction < 0)
    {
        if (start + slen > selflen)
            return 0;
    }
    //字符串尾部匹配(即endswith)
    else
    {
        if (end - start<slen || start>selflen)
            return 0;
        if (end - slen > start)
            start = end - slen;
    }
    if (end - start >= slen)
        //mcmcmp函数用于比较buf1与buf2的前n个字节
        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)
{
    //调用_string_tailmatch函数,参数+1表示字符串尾部匹配
    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)
{
    //调用_string_tailmatch函数,参数-1表示字符串头部匹配
    int result = _string_tailmatch(str, suffix, start, end, -1);
    return static_cast<bool>(result);
}

//上面均为startswith以及endswith的方法实现,可以直接复制粘贴
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;
}
  • 运行结果如下
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值