如何修剪含多个'\0'的std::string,使其size()与length()匹配C字符串长度?
修剪含'\0'的std::string使其size()匹配C字符串长度
你的示例确实证明了std::string可以存储多个'\0'字符,要让它的size()和length()反映第一个'\0'之前的实际长度(也就是C风格字符串的长度),标准库没有专门的"内置修剪方法",但可以用两种简单方式实现:
方式一:查找并截断原字符串
用std::string::find定位第一个'\0'的位置,再通过resize直接截断字符串:size_t first_null = s.find('\0'); if (first_null != std::string::npos) { s.resize(first_null); }执行后原字符串的
size()和length()会直接变为第一个'\0'之前的字符数。方式二:构造新的目标字符串
利用std::string的构造函数特性——传入C风格字符串时,会自动在第一个'\0'处停止读取:std::string trimmed_str(s.c_str());这种方式会生成一个全新的字符串,新字符串的长度就是你需要的C风格字符串长度,原字符串不会被修改。
测试修改后的代码(以方式一为例):
#include <iostream> #include <string> int main(int argc, char **argv) { std::string s; s = "abc"; s[1] = '\0'; size_t first_null = s.find('\0'); if (first_null != std::string::npos) { s.resize(first_null); } std::cout << "'" << s << "', " << s.size() << ", " << (int) s[1]; }
输出结果为:'a', 1, 0,完全符合预期。
内容的提问来源于stack exchange,提问作者no one special
相关产品推荐
相关产品推荐

