用字符分割字符串? [英] Split string by a character?

查看:158
本文介绍了用字符分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用":"字符分割字符串,例如"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.

  1. 分割字符串并存储到int数组中:

  1. 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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆