And*_*ong 1 c c++ string performance null-terminated
我不一定要这样做,但我很好奇.在C/C++是有办法来定义串的终止子等比空终止?例如,是否可以写这个,
char* str = "123456|ABCDEF";
char* foo = str;
char* bar = strstr(str, "|") + 1;
// do something here to define '|' as a terminator
std::cout << foo << std::endl;
std::cout << bar << std::endl;
// undo pipe-as-terminator definition
Run Code Online (Sandbox Code Playgroud)
得到输出,
123456
ABCDEF
Run Code Online (Sandbox Code Playgroud)
?
如果不能,那么有没有任何办法让指针到缓冲区的部分,不分配/复印内存,无需修改缓冲区,即覆盖|s到\0S'
您可以编写一个字符串引用包装器,其中包含指向子字符串和大小的指针,然后使用write而不是operator<<:
// Sketch
struct StringRef {
const char* start;
std::size_t length;
// add code to initialize the object out of the substring
};
std::ostream& operator<<(std::ostream& o, const StringRef& s) {
return o.write(s.start,s.length);
}
Run Code Online (Sandbox Code Playgroud)