C++完全复制要字符串的字符列表,而不会忽略多个空格

C++ copy list of chars to string exactly without ignoring multiple whitespace

本文关键字:空格 列表 复制 字符串 字符 C++      更新时间:2023-10-16

我有一个字符列表,L:

{'h','e','l','l','o',' ', ' ',' ', 'm', 'y', ' ', ' ',' ', 'n','a','m','e'};

我想将其复制到字符串中。我想保持三重空格并在下面得到一个字符串 S:

"hello   my   name"

我试过这个:

string S(L.begin(), L.end()); 

但它以某种方式删除了三个空格并给了我单个空格,S 变成了:"你好我的名字"。 我尝试一一迭代:

string S = "";
for (auto it = L.begin(); it!=L.end(); it++){
S+=*it;
}

我仍然得到带有单个空格的"你好我的名字"。 我尝试将列表存储在字符向量中,然后通过循环遍历向量并逐个推回字符串变成字符串,但它仍然忽略多个空格。如何告诉计算机将列表的字符逐字复制到字符串中,而不管有多少个连续的空格字符。即使它只是一个空格列表,我也想得到一串空格。有什么帮助吗?

请参阅下面的代码:

int main() {
list<char> L {'h', 'e', 'l', 'l', 'o', ' ', ' ', ' ', 'm', 'y', ' ', ' ', ' ', 'n', 'a', 'm', 'e'};
string S_attempt1(L.begin(), L.end());
string S_attempt2 = "";
for (auto it = L.begin(); it != L.end(); it++){
S_attempt2+=*it;
}
cout << S_attempt1 << endl;
cout << S_attempt2 << endl;
}

对于某些字符串,我得到的字符串是"hello my name"而不是"hello my name"

这似乎工作正常,并且不会忽略空格:

string convertToString(list<char> lst, int size) 
{ 
string s = ""; 
for (auto const& i : lst) {
s = s + i;
}
return s; 
} 

像这样运行这个...

list<char> L = {'h', 'e', 'l', 'l', 'o', ' ', ' ', ' ', 'm', 'y', ' ', ' ', ' ', 'n', 'a', 'm', 'e'}; 
int L_size = sizeof(L) / sizeof(char); 
string s_L = convertToString(L, L_size);
cout << s_L << endl;

。返回预期的输出。