我有一个字符列表,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;
}
我仍然用单个空格获得“你好我的名字”。我尝试将列表存储在chars的向量中,然后通过遍历向量并逐一推回字符串而变成字符串,但它仍然忽略多个空格。我如何告诉计算机将列表中的字符逐字复制到字符串,而不管有多少个连续的空白字符。即使只是空格列表,我也想获取一串空格。有帮助吗?
请参见下面的代码:
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;
...返回期望的输出。