提供 `slice` 操作的 C++ 字符串类(不创建新的字符串拷贝)

标签 c++ string slice

是否存在提供切片操作且不创建新字符串拷贝的现有 C++ 字符串类? (有点像 go 编程语言中的 string)

awesome::CString s = "this is an awesome string";
awesome::CString s1 = s.Mid(8, 10); // contains "an awesome" but not new copy
if (s1 == "an awesome") {
    awesome::CString s2 = s.Mid(11); // contains " string"
}
std::string str = s.str(); // create a copy that is the usual string

我认为 go 的实现对于解析字符串数据(例如解析 APDU)更有效

最佳答案

虽然很快,但我相信存储引用的类可能是最好的解决方案。

这并不完全如您所愿,因为仍然会制作一个临时拷贝来为您提供子字符串。但结果符合预期,我认为它在安全性和可读性之间取得了平衡,没有使用 hack 等,因为 STL 明确表示不要对底层字符串存储做出假设。

#include <iostream>
#include <cstring>

using namespace std;

class stringRef {
   public:
    string & src;
        size_t i;
        size_t s;
        stringRef(string &ssrc, size_t i_pos, size_t i_spam):src(ssrc){
            i=i_pos;
            s=i_spam;
        }
        operator const string(){
        return string(src.substr(i, s));
        }
    };

int main() {
    string s("this is an awesome string");
    stringRef s1(s, 8, 10);       //initializes [s1] bound to [s]
    cout << (string)s1 << endl;   //prints [s1]
    s=" quite a cool workaround"; //modifies [s]
    cout << (string)s1 << endl;   //prints [s1]
    return 0;
}

将输出:

an awesome
 cool work

从那里你可以改进类(class)做任何你想做的=)

关于提供 `slice` 操作的 C++ 字符串类(不创建新的字符串拷贝),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23001915/

相关文章:

‘operator ’ 的 C++ 不明确重载

c++ - Rust 中从 extern "C"方法返回动态字符串以供 C 或 C++ 使用的最佳方法

c++ - 在 Eclipse 中设置 C++ 构建工作目录

python - 如何将 .txt 文件的内容分配给 Python 中的字符串变量?

c# - 为什么没有 string.Split(string) 重载?

arrays - Go:反序列化数组字符串

带逗号的 Python 数组切片?

c++ - 直方图格式

string - 何时在 Go 中使用 []byte 或 string?

python - 将列表变量写入文件