簡體   English   中英

C ++,從字符串到char數組的轉換

[英]C++, conversion from string to char array

我想執行上述操作,但是我想確保char數組與手邊的字符串大小完全相同。

因此,真正的問題是,如何制作一個在運行時將要確定大小的數組?

在免費存儲區上分配內存,並一次性復制字符串:

std::string s("abcdef");

...
char* chars=strdup(s.c_str());

當然,您需要手動釋放內存。 文檔,例如在手冊頁上 正如@Loki提到的: 釋放此內存是通過free(chars) ,而不是通過delete 另外,您需要包括<cstring>標頭。

如果您想留在c ++世界中,請使用vector ; 它可以用兩個迭代器創建,以從中復制數據,並在堆上分配, 自行清理。 那不是一種享受嗎?

std::vector<char> vec( s.begin(), s.end() );

您可以使用“ new”運算符在運行時創建一個大小已知的數組:

char* res = new char[str.size()+1];
strncpy(res, str.c_str(), str.size()+1);
std::string s = "hello";
char* c = new char[s.length() + 1]; // '+ 1' is for trailing NULL character.

strcpy(c, s.c_str());
#include <string>

int main(int argc, char *argv[])
{
   std::string random_data("This is a string");

   char *array=new char[random_data.size()+1];

   // do stuff

   delete[] array;

   return 0;
}

嘗試:

char* res = new char[str.size()+1]();   // Note the () makes sure it is '0' filled.
std::copy(str.begin(), str.end(), res); // Don't need to copy the '\0' as underlying
                                        // array already has '\0' at the end position.
...
delete [] res;                          // Must not forget to delete.

或:(最好)

std::vector<char> res(str.begin(), str.end());

或者:如果您只想調用C函數,請執行以下操作:

str.c_str()

使用strlen()查找字符串的長度,然后使用malloc()一個具有該大小的char數組。

暫無
暫無

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

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