C++20: 像Python一样split字符串

概要

Python 的字符串天生支持 split( ) 操作,支持单个字符或字符串作为分隔符。 C++ 在这方面显得很笨拙,但是在 C++20 下经过一番尝试,还是能够提供类似的简洁调用。

Python 代码

python 复制代码
s = '0,11,336,23,370'

nums = s.split(',')
for n in nums:
    print(n)

print('---')

items = s.split('11,')
for i in items:
    print(i)

基于 C++20 的实现

  • 使用了 std::string_view, 避免了原始字符串的拷贝
  • 使用了组合,而不是继承的方式,把 split( ) 函数,与原始的字符串 str 进行组合,也就是分别作为 MyString 类的成员函数和数据成员
cpp 复制代码
class MyString {
private:
    std::string data;

public:
    MyString(const std::string& str) : data(str) {}
    MyString(std::string&& str) : data(std::move(str)) {}
    MyString(const char* str) : data(str) {}

    // 提供 split 方法
    std::vector<std::string> split(const std::string& delimiter) const {
        std::vector<std::string> result;
        size_t start = 0;
        size_t end = 0;

        while ((end = data.find(delimiter, start)) != std::string::npos) {
            result.emplace_back(data.substr(start, end - start));
            start = end + delimiter.length();
        }
        result.emplace_back(data.substr(start)); // 添加最后一部分
        return result;
    }

    // 提供 std::string 的接口
    const std::string& str() const { return data; }
    operator const std::string&() const { return data; } // 隐式转换为 std::string
};

调用代码 - C++

cpp 复制代码
int main() {
    MyString s("0,11,336,23,370");

    // 按 ',' 分割
    auto nums = s.split(",");
    for (const auto& n : nums) {
        std::cout << n << '\n';
    }

    std::cout << "---\n";

    // 按 "11," 分割
    auto items = s.split("11,");
    for (const auto& i : items) {
        std::cout << i << '\n';
    }

    return 0;
}

总结

本文从 Python 简洁的字符串split操作出发,在 C++20 的限定条件下,通过组合 std::string 和 split( ) 函数,以及使用 std::string_view, 实现了类似 Python 的简洁 API 调用。

相关推荐
用户83562907805111 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805111 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生19 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师20 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码20 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf20 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python