(C++)将指针分配给字符串的一部分
(C++) assigning pointer to part of string
我刚刚进入本机应用程序的世界,我不知道如何将指针分配给字符串的一部分。
例如,我有以下内容:
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.优点和缺点
当然,你可以用struct
ures的形式处理这些"链接",只需花点时间思考一下你为什么要这样做。这种方法有什么优势?如果内存效率是你这么做的唯一原因,那么你很可能会进入过早优化的地下城。
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:生存期。。。如果你的字符串不见了,你仍然保留着你的Node
s,这些指针只会变成一堆无效/悬空指针。
问题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还包含一个示例实现。
- C++:如何使函数只返回作为列表一部分的字符串
- 如何将字符串的一部分转换为整数
- 如何有效地将一个大std::字符串的一部分转换为float
- 需要从字符串数组的一部分访问元素
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- boost::async_write 跳过字符串的一部分
- 如何在不复制的情况下比较字符串的一部分?
- 我如何在QT中获得字符串的一部分
- 如何在C++中比较数组中字符串的一部分的字符串
- 如何在 c++ 中拆分字符串的一部分
- 字符数组仅占用字符串的一部分
- 如何用双C 替换字符串的一部分
- 如何在字符串中选择句子的一部分 (C++)
- 如何拆分 QString 并将一部分字符串保存在浮点数的向量中
- 为什么C 正则只能找到JavaScript Regex在字符串中找到的一部分
- 字符串操纵和忽略字符串的一部分
- 在C 中更新字符串的一部分
- 有条件地确定字符串是否是数组的一部分
- 尝试在 Cocos2d-X C++中设置一个带有整数作为其字符串一部分的 CCLabelTTF