簡體   English   中英

在 C++ 中將 int[] 轉換為 String

[英]Converting int[] to String in C++

我有一個字符串定義為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());

我使用atoi將初始字符串轉換為int數組。 現在我不確定如何制作字符串。 讓我知道是否有更好的方法。

你可以寫一個小函數

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;
}

未經測試!

稍微不同的方法

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();
}

做這個:

  char data_bytes[] = { '0', '0', '1', '1', '0', '0', '3', '3', '\0'};
  std::string header(data_bytes, 8);

或者,您可能想這樣做:

  std::stringstream s;
  s << data_bytes;
  std::string header = s.str();

ideone 演示: http ://ideone.com/RzrYY


編輯:

data_bytes 中的最后一個\\0是必需的。 也可以在這里看到這個有趣的輸出: http : //ideone.com/aYtlL

PS:我之前不知道這個,感謝Ashot我通過實驗知道了這個區別!

 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]);

假設您使用的是“相當正常”的系統,其中'0''9'的數值是連續的,您可以遍歷每個元素並減去'0'

for(int i = 0; i < header.size(); ++i)
{
    header[i] -= '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' ) );

如果integ[]是整數數組,而s是我們希望獲得的最終字符串,

string s="";

for(auto i=0;i<integ.size()-1; ++i)
    s += to_string(ans[i]); 

cout<<s<<endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM