c++中怎么把string转化为数组

来源:互联网 发布:金蝶软件营销服务中心 编辑:程序博客网 时间:2024/06/05 23:58

前几天做搜狗在线笔试题的时候,碰到下面这样的输入:

1 2 3 4 5

也就是不确定个数的数字序列,这些数字由空格间隔。我想得到1,2,3,4,5组成的数组。

当时我对于这样的输入并不清楚如何正确快捷地进行处理,就查了下stackoverflow,的确找到了一个非常好的解决办法。

首先使用如下代码,把当前行读入到string变量line中。

getline(cin, line);
注意,getline并不读取换行符,它会把换行符discard!!!!!!。言外之意是,如果使用了getline之后,你再使用一个getchar(),getchar是读取不到换行符的,getchar会等待你输出新的字符。

相反,如果你使用cin>>line 读取输入到string变量line中之后,你再使用了一个一个getchar(),getchar()会直接读取换行符!!!

好吧,上面扯得有点远了,我们继续说下,如何把string转化为数组吧。


在这里我们直接上stackoverflow上面的问题和回答吧。

问题:

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,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 can do all these.

  1. Split a string and store into int array:

string str = "102:330:3133:76531:451:000:12:44412";for (int i=0; i<str.length(); i++){    if (str[i] == ':')        str[i] = ' ';}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}

2.Remove unneeded characters from the string before it's processed such as $ and #: just as the way handling : in the above.

注意:上面的代码,必须加入头文件<sstream>

0 0
原创粉丝点击