C++ 如何在C++中正确地将char数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26380695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to correctly converting char array to string in c++
提问by mans
I have these two set of char arrays:
我有这两组字符数组:
char t1[]={'1','2',' string convert(char * data)
{
return string(data);
}
',' string convert(char * data)
{
return string(data,data+4);
}
'};
char t2[]={'1','2','3','4'};
I want to write a function to convert them to string, but the string size for t1 should be 2 and for t2 should be 4.
我想编写一个函数将它们转换为字符串,但是 t1 的字符串大小应该是 2,t2 的字符串大小应该是 4。
std::string convert(char const(&data)[4])
{
return std::string(data, std::find(data, data + 4, 'template<size_t N>
std::string convert(char const(&data)[N])
{
return std::string(data, std::find(data, data + N, '#include <string>
#include <iostream>
std::string sconvert(const char *pCh, int arraySize){
std::string str;
if (pCh[arraySize-1] == '##代码##') str.append(pCh);
else for(int i=0; i<arraySize; i++) str.append(1,pCh[i]);
return str;
}
int main(){
char t1[]={'1','2','##代码##','##代码##'};
char t2[]={'1','2','3','4'};
std::string str = sconvert(t1, 4);
std::cout << str << " : " << str.size() << std::endl;
str = sconvert(t2, 4);
std::cout << str << " : " << str.size() << std::endl;
}
'));
}
'));
}
Does a good job for t1, but crashes on t2 (t2 is not null terminated).
对 t1 做得很好,但在 t2 上崩溃(t2 不是空终止)。
##代码##Does a good job for t2, but the size of generate string for t1 is 4 and not 2.
对 t2 来说做得很好,但是 t1 的生成字符串的大小是 4 而不是 2。
What is the best way to write a simple and fast function to do this correctly?
编写简单快速的函数以正确执行此操作的最佳方法是什么?
回答by Benjamin Lindley
You can take an array by reference. If you're only interested in arrays of size 4:
您可以通过引用获取数组。如果您只对大小为 4 的数组感兴趣:
##代码##If you want something more general, you can make it a template:
如果你想要更一般的东西,你可以把它变成一个模板:
##代码##回答by Ivailo Tanusheff
If you know what is the length of the character array I may suggest you the following:
如果您知道字符数组的长度是多少,我可能会建议您执行以下操作:
##代码##