用字符分割字符串? [英] Split string by a character?
问题描述
如何用":"
字符分割字符串,例如"102:330:3133:76531:451:000:12:44412
,并将所有数字放入一个int数组中(数字序列的长度始终为8个元素)?最好不要使用诸如boost的外部库.
How can I split a string such as "102:330:3133:76531:451:000:12:44412
by the ":"
character, and put all of the numbers into an int array (number sequence will always be 8 elements long)? Preferably without using an external library such as boost.
此外,我想知道如何在处理字符串之前从字符串中删除不需要的字符,例如"$"和#"?
Also, I'm wondering how I can remove unneeded characters from the string before it's processed such as "$" and "#"?
推荐答案
stringstream
可以完成所有这些操作.
stringstream
can do all these.
-
分割字符串并存储到int数组中:
Split a string and store into int array:
string str = "102:330:3133:76531:451:000:12:44412";
std::replace(str.begin(), str.end(), ':', ' '); // replace ':' by ' '
vector<int> array;
stringstream ss(str);
int temp;
while (ss >> temp)
array.push_back(temp); // done! now array={102,330,3133,76531,451,000,12,44412}
在处理字符串之前从字符串中删除不需要的字符,例如$
和#
:就像上面处理:
的方式一样.
Remove unneeded characters from the string before it's processed such as $
and #
: just as the way handling :
in the above.
PS:以上解决方案仅适用于不包含空格的字符串.要处理带空格的字符串,请基于此处/w/cpp/string/basic_string/find"rel =" nofollow noreferrer> std::string::find()
和
PS: The above solution works only for strings that don't contain spaces. To handle strings with spaces, please refer to here based on std::string::find()
and std::string::substr()
.
这篇关于用字符分割字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!