(C++)将指针分配给字符串的一部分



我刚刚进入本机应用程序的世界,我不知道如何将指针分配给字符串的一部分。

例如,我有以下内容:

std::string data = "put returns between paragraphsfor linebreak add 2 spaces at end_italic_ or **bold**indent code by 4 spacesbacktick escapes `like _so_`quote by placing > at start of line to make links";

单词CCD_ 1的第一个字符具有索引4。我的问题是如何指向单词return,而不将其复制到新字符串中。

谢谢。

编辑:

struct Node { 
     const char * ptrToNodeStart; 
     int nodeLen;
}

我找到了这个片段,但有人能告诉我如何使用它吗?

1。"内存高效"

"我的文本包含10k多个字符,我可能需要对单个文本进行1000+个链接,这不会真正提高内存效率"-假设你将有1000个长度为10000个字符的字符串,即10 mil字节=~9.54MB+假设有一些小开销,这肯定不会消耗超过10MB的内存

2.优点和缺点

当然,你可以用structures的形式处理这些"链接",只需花点时间思考一下你为什么要这样做。这种方法有什么优势?如果内存效率是你这么做的唯一原因,那么你很可能会进入过早优化的地下城。

3."如何将指针分配给字符串的一部分"

std::string str = "My simple string";
Node n;
n.ptrToNodeStart = &str[3];
n.nodeLen = 6;
// n is expected to refer to string "simple" here

但实际上并没有那么简单。str是具有自动存储持续时间的对象,一旦执行离开该范围,存储字符串的内存就会释放,即您有问题1:生存期。。。如果你的字符串不见了,你仍然保留着你的Nodes,这些指针只会变成一堆无效/悬空指针

问题2:由于没有null终止字符,因此无法将Node中的此指针视为字符串。如果你需要它,你很可能会得到C风格的易出错代码,这些代码会做一些邪恶的事情,比如:

std::string tempStr(n.nodeLen + 1, '');
memcpy(&tempStr[0], n.ptrToNodeStart, n.nodeLen);
// yehey !!! I can finally use this annoying Node as a normal string now ....

甚至更糟:

char *buffer = new char[n.nodeLen + 1];
memcpy(buffer, n.ptrToNodeStart, n.nodeLen);
buffer[n.nodeLen] = '';
// using buffer here ...
delete[] buffer;

我的建议:
  • 尽可能避免使用指针
  • 坚持使用标准库中整洁的对象
  • 转到std::string对象、std::vector<std::string> stringParts
  • 使用std::string::substr():

    std::string str = "My simple string";
    std::string part = str.substr(3,6);
    // part holds string "simple" now
    

您可以定义一个对象,该对象包含一对指向大字符串中开始和结束的迭代器。然后,给它一个类似字符串的接口。然而,当原始字符串超出范围时,迭代器将指向涅盘,您的问题可能会崩溃,因此使用它可能很危险。

class StringView {
public:
    typedef std::string::const_iterator iterator;
    typedef std::string::const_iterator const_iterator;
    typedef std::string::size_type size_type;
    StringView(std::string const& s, 
               size_type from, 
               size_type to): data_(&s), first_(from), last_(to) {}
    bool empty() const {return s.empty();}
    size_type length() const {return last_ - first_;}
    iterator begin() const {data_.begin() + first_;}
    iterator end() const {data_.begin() + last_;}
    // add more functions for strings here
private:
    std::string const* data_;
    std::string::size_type first_, last_;
};

当你开始做这件事时,你还可以看看Monoliths"Unstrung",它解释了为什么std::string类接口应该改进以及如何改进。

为了标准化,提出了一个string_view类。STLport还包含一个示例实现。

最新更新