C++之split字符串分割 -- strtok函数

在C++中没有直接对应的split函数,字符串分割可借助以下方法实现:

1、借助strtok函数

函数原型:char *strtok(char *s,const char *delim)

函数功能:以delim为分隔符分割字符串str

参数说明:str:要分隔的字符串;delim:分隔符

描述:strtok()用来将字符串分割成一个个片段,参数s指向将要被分隔的字符串,参数delim则为分隔字符串,当strtok()在参数s的字符串中发现到参数delim的分隔字符时,则会将该字符改为'\0'字符,在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL.每次调用成功则返回被分隔片段的指针。

返回值:从str开头开始的一个个被分割的字符串。当没有被分割时则返回null

代码1:直接使用strtok函数分割char*类型的字符串

​​#include <iostream>
#include <string.h>  // for strtok declare, C Language library, also can use #include <cstring>
using namespace std;

int main()
{
    char s[] = "This is a sentence with   dsf das ag #@!";
    char *p;
    const char *delim = " ";
    p = strtok(s, delim);
    cout<<"======The result======"<<endl;
    while(p)  //while(p!=NULL)
    {
        cout << p << endl;
        p = strtok(NULL, delim);
    }
    return 0;
}

​

​

​

​

/* strtok是一个线程不安全的函数,因为它使用了静态分配的空间来存储被分割的字符串位置   
 * 线程安全的函数叫strtok_r,ca   
 * 运用strtok来判断ip或者mac的时候务必要先用其他的方法判断'.'或':'的个数,
 * 因为用strtok截断的话,比如:"192..168.0...8..."这个字符串,strtok只会截取四次,中间的...无论多少都会被当作一个key
 */

代码2:借助strtok分割string类型的字符串,将结果保存在vector<string>中, 即用于取回分割的字符串

思路:先将整个string字符串转换为char*类型,分割后得到char*类型的子字符串,将子字符串转换为string类型,并存入结果数组中。

#include <iostream>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
vector<string> Split(const string &str, const string &delim)
{
    vector<string> res;
    if(str == "")
        return res;
    char *strs = new char[str.length() + 1];
    strcpy(strs, str.c_str());
    char *d = new char[delim.length() + 1];
    strcpy(d, delim.c_str());

    char *p = strtok(strs, d);
    while(p)
    {
        string s = p;
        res.push_back(s);
        p = strtok(NULL, d);
    }
    return res;
}

int main()
{
    string s1 = " the sky is blue!  one parameter        ll?";
    string delim = " ";

    vector<string> s2 = Split(s1, delim);
    cout<<"======The result======"<<endl;
    for(int i=0; i<s2.size(); i++)
        cout<<s2[i]<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值