现代C方式将字符串复制到char *
发布时间:2020-12-16 06:48:59 所属栏目:百科 来源:网络整理
导读:这样做的现代方法是什么?像 cstring这样的标题不推荐使用,并且某些编码样式禁止使用“类C”函数.我有三种做同样事情的方法.现代C中哪一个最惯用? 1.使用迭代器并包含null终止符 { std::string test{"hello,world!"}; char* output = new char[test.size()
这样做的现代方法是什么?像< cstring>这样的标题不推荐使用,并且某些编码样式禁止使用“类C”函数.我有三种做同样事情的方法.现代C中哪一个最惯用?
1.使用迭代器并包含null终止符 { std::string test{"hello,world!"}; char* output = new char[test.size() + 1]; std::copy(test.begin(),test.end(),output); output[test.size() + 1] = ' '; std::cout << output; delete output; } 2.使用包含空终止符的c_str() { std::string test{"hello,world!"}; char* output = new char[test.size() + 1]; std::copy(test.c_str(),test.c_str() + std::strlen(test.c_str()),output); std::cout << output; delete output; } 3.使用std :: strcpy { std::string test{"hello,world!"}; char* output = new char[test.size() + 1]; std::strcpy(output,test.c_str()); std::cout << output; delete output; } 我不希望看起来像一个面试官说“你用strcpy,你必须是C程序员”的菜鸟. 解决方法
获得连续缓冲区的现代安全前C 17方法是std :: vector.
std::string test{"hello,world!"}; std::vector<char> output(test.c_str(),test.c_str()+test.size()+1); // use output.data() here... 从C 17开始,std :: string有一个非const data()重载. std::string test{"hello,world!"}; char * p = test.data(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |