C++ 字符串处理3-实现starts_with和ends_with的字符串判断功能

1. 关键词

C++ 字符串处理 starts_with ends_with std::string 跨平台

2. C++20及之后

C++20标准开始,STL已经提供了starts_withends_with函数,可以直接使用。在 <string>头文件中,可以直接作为字符串对象的成员函数使用。

官方API文档: https://en.cppreference.com/w/cpp/string/basic_string

3. C++20之前

C++20之前, STL本身不支持starts_with和ends_with的功能,开发者需要自己实现,可参考以下实现代码。

3.1. strutil.h

#include <string>
namespace cutl
{
    /**
     * @brief Check if a string starts with a given substring.
     *
     * @param str the string to be checked.
     * @param start the substring to be checked.
     * @param ignoreCase whether to ignore case when comparing, default is false.
     * @return true if the string starts with the substring, false otherwise.
     */
    bool starts_with(const std::string &str, const std::string &start, bool ignoreCase = false);
    /**
     * @brief Check if a string ends with a given substring.
     *
     * @param str the string to be checked.
     * @param end the substring to be checked.
     * @param ignoreCase whether to ignore case when comparing, default is false.
     * @return true if the string ends with the substring, false otherwise.
     */
    bool ends_with(const std::string &str, const std::string &end, bool ignoreCase = false);
} // namespace cutl

3.2. strutil.cpp

#include <cctype>
#include <algorithm>
#include "strutil.h"

namespace cutl
{
    bool starts_with(const std::string &str, const std::string &start, bool ignoreCase)
    {
        int srclen = str.size();
        int startlen = start.size();
        if (srclen < startlen)
        {
            return false;
        }

        std::string temp = str.substr(0, startlen);
        if (ignoreCase)
        {
            return to_lower(temp) == to_lower(start);
        }
        else
        {
            return temp == start;
        }
    }

    bool ends_with(const std::string &str, const std::string &end, bool ignoreCase)
    {
        int srclen = str.size();
        int endlen = end.size();
        if (srclen < endlen)
        {
            return false;
        }

        std::string temp = str.substr(srclen - endlen, endlen);
        if (ignoreCase)
        {
            return to_lower(temp) == to_lower(end);
        }
        else
        {
            return temp == end;
        }
    }
} // namespace cutl

3.3. 测试代码

#include "common.hpp"
#include "strutil.h"

void TestStartswithEndswith()
{
    PrintSubTitle("TestStartswithEndswith");

    std::string str1 = "Hello, world!";
    std::string str2 = "GOODBYE, WORLD!";
    std::cout << str1 << " start with hello : " << cutl::starts_with(str1, "hello") << std::endl;
    std::cout << str1 << " start with hello ignoreCase: " << cutl::starts_with(str1, "hello", true) << std::endl;
    std::cout << str2 << " end with world! : " << cutl::ends_with(str2, "world!") << std::endl;
    std::cout << str2 << " end with world! ignoreCase: " << cutl::ends_with(str2, "world!", true) << std::endl;
}

3.4. 运行结果

---------------------------------------TestStartswithEndswith---------------------------------------
Hello, world! start with hello : 0
Hello, world! start with hello ignoreCase: 1
GOODBYE, WORLD! end with world! : 0
GOODBYE, WORLD! end with world! ignoreCase: 1

3.5. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

<think>嗯,用户想了解C++中与字符串操作相关的函数列表及其用法。首先,我需要回忆一下C++标准库中关于字符串处理的部分,主要是<string>头文件里的内容。然后,考虑常见的字符串操作函数,比如构造、连接、查找、子串、替换、比较、大小写转换等。 首先,C++的std::string类提供了很多成员函数。比如构造函数,可以用字符串字面量初始化。然后是appendoperator+用于连接字符串。findrfind用于查找子串的位置,substr用来提取子串。replace可以替换部分字符串,compare用于比较。还有处理大小写的部分可能需要标准库外的函数,比如tolowertoupper,但这些在<cctype>里,需要结合算法使用。 另外,C++17引入了新的函数,比如starts_withends_with,这些在检查字符串开头或结尾时很有用。还有字符串分割,虽然标准库没有直接提供,但可以通过其他方法实现,比如结合findsubstr。 接下来要确保回答的结构清晰,分点列出常用函数,每个函数给出示例说明。同时,用户提到了引用的需求,需要引用站内的资料。比如,在提到C++17的结构化绑定时,可以引用参考中的[^1],而在其他部分如果有相关的内容也需要正确引用。 可能还需要生成相关问题,比如如何分割字符串处理UTF-8字符串的方法、性能优化的建议等。这些问题应该与字符串操作相关,帮助用户进一步学习。 需要检查是否有遗漏的重要函数,比如c_str()用于获取C风格字符串,或者capacity()、reserve()等内存管理相关的函数。不过用户可能更关注操作函数,所以重点放在操作上。 另外,用户的问题里提到“函数列表用法”,所以每个函数需要简要说明用途示例。确保示例代码正确,比如使用正确的语法正确的成员函数名称。比如substr的起始位置长度参数是否正确。 最后,确认是否覆盖了C++11、C++17等新标准引入的函数,比如starts_withC++20的,所以需要注明版本。如果有错误的地方需要修正,比如字符串分割的例子是否正确,循环条件是否处理了所有情况。 总结一下,回答的结构应该是先介绍std::string的基本信息,然后分点列出各个函数,每个函数给出示例说明,引用相关文献,最后生成相关问题。确保使用正确的中文表达,避免技术术语错误,并且代码示例正确无误。</think>以下是C++中常用的字符串操作函数及用法说明: ### 一、基础字符串操作 1. **构造与赋值** ```cpp std::string s1 = "Hello"; // 直接初始化 std::string s2(5, &#39;A&#39;); // 创建含5个&#39;A&#39;的字符串 s1.assign("World", 3); // 赋值为"Wor" ``` 2. **字符串连接** ```cpp std::string s3 = s1 + " " + s2; // 使用+运算符 s1.append(" C++"); // 追加内容 ``` 3. **字符串查找** ```cpp size_t pos = s1.find("or"); // 查找子串位置 size_t rpos = s1.rfind(&#39;o&#39;); // 从后向前查找 if (pos != std::string::npos) { // 找到匹配项 } ``` 4. **子串操作** ```cpp std::string sub = s1.substr(2, 4); // 从索引2取4个字符 s1.replace(0, 5, "Hi"); // 替换前5个字符为"Hi" ``` ### 二、字符串特性操作 1. **容量查询** ```cpp if (!s1.empty()) { // 检查是否为空 int len = s1.length(); // 获取字符串长度 s1.resize(10); // 调整字符串大小 } ``` 2. **字符级访问** ```cpp char c = s1[2]; // 通过索引访问 s1.back() = &#39;!&#39;; // 修改最后一个字符 ``` ### 三、现代C++特性(C++17/20) 1. **字符串视图** ```cpp std::string_view sv = "View"; // 轻量级只读视图[^1] ``` 2. **前缀/后缀检查** ```cpp bool starts = s1.starts_with("He"); // C++20新特性 bool ends = s1.ends_with("!"); // C++20新特性 ``` ### 四、实用代码示例 ```cpp // 字符串分割函数示例 std::vector<std::string> split(const std::string& s, char delim) { std::vector<std::string> tokens; size_t start = 0, end = 0; while ((end = s.find(delim, start)) != std::string::npos) { tokens.push_back(s.substr(start, end - start)); start = end + 1; } tokens.push_back(s.substr(start)); return tokens; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌尘(MoChen)

爱打赏的人技术成长更快哦~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值