在 C++ 中将 int[] 转换为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5223066/
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
Converting int[] to String in C++
提问by Manoj
I have a string defined as std::string header = "00110033";now I need the string to hold the byte values of the digits as if its constructed like this
我定义了一个字符串,std::string header = "00110033";现在我需要该字符串来保存数字的字节值,就好像它是这样构造的
char data_bytes[] = { 0, 0, 1, 1, 0, 0, 3, 3};
std::string header = new std::string(data_bytes, 8).c_str());
I converted the initial string to intarray using atoi. Now i'm not sure how to make the string out of it. Let me know if there is any better approach.
我int使用将初始字符串转换为数组atoi。现在我不确定如何制作字符串。让我知道是否有更好的方法。
采纳答案by ultifinitus
you could write a little function
你可以写一个小函数
string int_array_to_string(int int_array[], int size_of_array) {
string returnstring = "";
for (int temp = 0; temp < size_of_array; temp++)
returnstring += itoa(int_array[temp]);
return returnstring;
}
untested!
未经测试!
a slightly different approach
稍微不同的方法
string int_array_to_string(int int_array[], int size_of_array) {
ostringstream oss("");
for (int temp = 0; temp < size_of_array; temp++)
oss << int_array[temp];
return oss.str();
}
回答by Nawaz
Do this:
做这个:
char data_bytes[] = { '0', '0', '1', '1', '0', '0', '3', '3', ' std::stringstream s;
s << data_bytes;
std::string header = s.str();
'};
std::string header(data_bytes, 8);
Or maybe, you want to do this:
或者,您可能想这样做:
char data_bytes[] = { 0, 0, 1, 1, 0, 0, 3, 3};
std::string str;
for(int i =0;i<sizeof(data_bytes);++i)
str.push_back('0'+data_bytes[i]);
Demo at ideone : http://ideone.com/RzrYY
ideone 演示:http://ideone.com/RzrYY
EDIT:
编辑:
Last \0in data_bytes is necessary. Also see this interesting output here: http://ideone.com/aYtlL
\0data_bytes 中的最后一个是必需的。也可以在这里看到这个有趣的输出:http: //ideone.com/aYtlL
PS: I didn't know this before, thanks to AshotI came to know this difference by experimenting!
PS:我之前不知道这个,感谢Ashot我通过实验知道了这个区别!
回答by UmmaGumma
for(int i = 0; i < header.size(); ++i)
{
header[i] -= '0';
}
回答by Mark B
Assuming you're using a "fairly normal" system where the numeric values of '0'to '9'are consecutive, you can just iterate over each element and subtract '0':
假设您使用的是“相当正常”的系统,其中'0'to的数值'9'是连续的,您可以迭代每个元素并减去'0':
std::string header( data_bytes, data_bytes + sizeof( data_bytes ) );
std::transform( header.begin(), header.end(), header.begin(),
std::bind1st( std::plus< char >(), '0' ) );
回答by Eugen Constantin Dinca
You can do this:
你可以这样做:
string s="";
for(auto i=0;i<integ.size()-1; ++i)
s += to_string(ans[i]);
cout<<s<<endl;
回答by Pe Dro
If integ[]is the integer array, and sis the final string we wish to obtain,
如果integ[]是整数数组,而s是我们希望获得的最终字符串,
##代码##
