簡體   English   中英

使用字符數組初始化字符串

[英]Initialize a String using a Character Array

假設我有一個字符數組,我想將其轉換為字符串。 是否可以使用該字符數組初始化字符串,而無需遍歷數組並將每個字符添加到字符串中?

只需分配它們:

std::string str = char_array;

當然,這仍然會在內部遍歷字符串。 無法避免這種情況(但這非常有效)。

只需使用std::string::string(char const*)構造函數即可,因為C樣式的數組隱式衰減到指針,因此可以使用該構造函數:

char my_character_array[] = "Hello, world!";
std::string my_string(my_character_array);

確保數組包含一個空字符,否則該行為是不確定的。


如果您有std::arraystd::vector而不是C樣式的數組,請使用以下命令:

std::string my_string(my_character_array.begin(), my_character_array.end());

如果您已經有了一個std::string對象,請看一下std::copy

參見構造函數4和5

char s[] ={'a','b','c', '\0'};

std::string str(s);

暫無
暫無

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

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