我刚刚进入 native 应用程序世界,我不知道如何将指针分配给字符串的一部分。
例如我有以下内容:
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";
单词 return
的第一个字符的索引为 4,最后一个字符的索引为 10。我的问题是如何在不复制的情况下指向单词 return
到新字符串。
谢谢。
编辑:
struct Node {
const char * ptrToNodeStart;
int nodeLen;
}
我找到了这个片段,但谁能解释一下如何使用它。
最佳答案
1. “内存高效”
“我的文本包含 10k+ 个字符,我可能需要对单个文本做 1000+ 个链接,这不会真正节省内存” - 假设您将有 1000 个长度为 10000 的字符串字符,即 1000 万字节 = ~9.54MB + 假设有一些小的开销,这绝对不会消耗超过 10MB 的内存
2.优点和缺点
当然,您可以使用 struct
形式的这些“链接”当然,花点时间想想你为什么要这样做。这种方法有什么优势?如果内存效率是您这样做的唯一原因,那么您很可能进入了过早优化的地牢。
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: lifetime ... 如果您的字符串走了,你仍然保留你的 Node
s,这些变成一堆无效/悬挂指针。
问题 2: 由于没有空终止符,您无法处理 Node
中的这个指针作为一个字符串。如果您需要它,您很可能最终会得到 C 风格的容易出错的代码,这些代码会做一些坏事,例如:
std::string tempStr(n.nodeLen + 1, '\0');
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] = '\0';
// 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
关于c++ - (C++) 将指针分配给字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23090901/