数字字符串的分割

必看:C语言strtok()分割函数详解

数字字符串的输入:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    vector<string> vec;//["20,30,40", 50,60,70", "80,90,100"]
    string str;
    //while(getline(cin, str))//用getline可以输入空格,只用cin代表遇到空格即结束
    while(cin >> str)//输入后enter+ctrl+Z+enter
        vec.push_back(str);
    for(int i = 0; i < vec.size(); i++)
        cout << vec[i] << endl;
    system("pause");
    return 0;
}

在这里插入图片描述

对数字字符串进行分割:

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>  //sscanf()在C语言中包含在此头文件中
#include <string.h> //strtok()在C语言中包含在此头文件中

using namespace std;

int main()
{
    string str;
    cout<<"Input a numbers string with , :"<<endl;
    while(cin >> str)
    {
        //string转化为C字符串char *,这一步C++到C的转换很重要
        char *s = (char *)str.c_str();
        const char *split = ",";
        //以逗号为分隔符拆分字符串,第一次调用后相当于用NULL替换了第一个逗号,
        char *p = strtok(s, split);

        vector<int> nums;
        int num;
        while(p != NULL)
        {
            //将第一个子C字符串char*转化为int
            sscanf(p, "%d", &num);
            nums.push_back(num);
            p = strtok(NULL, split);//多次调用分割函数,每次都以NULL作为子串起点
        }

        cout<<"Output:"<<endl;
        for(int i = 0; i < nums.size(); i++)
        {
            cout << nums[i] << " ";
        }
    }
    return 0;
}

在这里插入图片描述

#include <iostream>
#include <stdio.h> 
#include <string.h> //strtok()函数包含在此头文件

int main () 
{ 
    char str[] ="a,b3c,cf,d*e"; 
    const char * split = ","; 
    char * p; 
    p = strtok (str, split); 
    while(p != NULL) 
    { 
        printf ("%s\n", p); 
        p = strtok(NULL, split); 
    } 
    system("pause");
    return 0; 
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值