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 调用。

相关推荐
木子杳衫42 分钟前
【软件开发】管理类系统
python·web开发
程序员小远4 小时前
银行测试:第三方支付平台业务流,功能/性能/安全测试方法
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
Predestination王瀞潞4 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力5 小时前
C++继承
开发语言·c++
猫头虎6 小时前
如何查看局域网内IP冲突问题?如何查看局域网IP环绕问题?arp -a命令如何使用?
网络·python·网络协议·tcp/ip·开源·pandas·pip
沿着路走到底6 小时前
python 基础
开发语言·python
江公望7 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
烛阴8 小时前
武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法
前端·python
逆小舟9 小时前
【C/C++】指针
c语言·c++·笔记·学习
江公望9 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml