C++中拆分以空格分隔的字符串中的数字

C++拆分以空格分隔的字符串中的数字
 
算法需求:
做公司笔试题时,总是会遇到卡输入的题目。比如“第二行为n个整数,每个整数以空格隔开”,这时就要注意了,很有可能题目想表达的意思就是输入一个字符串,字符串中含有以空格隔开的数字

 
 
算法代码如下:

//循环处理要拆分的字符串s1,每次循环把下标0到空格前一个位置的数字字符复制下来并
//转换成数字加到数组中,再删除s1中已经分离的数字字符和其后的一个空格
    string s1 ;  //要拆分的字符串
    getline(cin , s1); //因为有空格,所以要用getline函数
    vector<int> res; 
    while (!s1.empty())
    {
        if (s1.find(" ") == string::npos) //如果没有空格了,则只剩下最后一个整数字符,转换为数字加入数组并清空字符串,使循环结束
        {
            res.push_back(stoi(s1));
            s1.clear();
            break;
        }
        string s_temp = s1.substr(0, s1.find(" "));
        res.push_back(stoi(s_temp));
        s1.erase(0, s1.find(" ") + 1); //要删掉空格,所以要s.find(" ") + 1
    }

 
 
验证代码如下:


#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    string s1;
    getline(cin, s1);
    vector<int> res;
    while (!s1.empty())
    {
        if (s1.find(" ") == string::npos)
        {
            res.push_back(stoi(s1));
            s1.clear();
            break;
        }
        string s_temp = s1.substr(0, s1.find(" "));
        res.push_back(stoi(s_temp));
        s1.erase(0, s1.find(" ") + 1);
    }
    for (auto &a : res)
    {
        cout << a << endl;
    }
    return 0;
}

 
 
希望能帮到大家,祝大家都能拿到满意的offer

猜你喜欢

转载自blog.csdn.net/weixin_37987487/article/details/82533884