C++字符串分割

本文介绍了四种在C++中分割字符串的方法:1) 自定义split函数,2) 使用stringstream,3) 利用istringstream,4) 应用getline。每种方法都有其特点,例如stringstream不适用于非空格分隔,而getline则无法处理连续的分隔符。通过这些方法,开发者可以根据实际需求灵活处理字符串分割问题。
摘要由CSDN通过智能技术生成

1. 自己实现split()

void split(const char *s, vector<string> &strs, char delim = ' ') {
    if(s == nullptr) {
        return;
    }

    const char *head, *tail;
    head = tail = s;

    while(*head != '\0') {
        while(*head != '\0' && *head == delim) {
            head++;
        }

        tail = head;
        while(*tail != '\0' && *tail != delim) {
            tail++;
        }

        if(head != tail) {
            strs.push_back(string(head, tail));
            head = tail;
        } else {
            break;
        }
    }
}

将字符串s按照delim代表的字符分割,并且放入vector中。

搜索过程中在stackoverflow上,发现了另外两个简单明了的办法。

2. stringstream

int main() {
    string str= "I love world!";
    string str_temp;
    stringstream ss;
    str>>ss;
    while(!ss.eof())
    {
    	ss>>str_temp;
    	cout<<str_temp<<endl;
	}
}

这个方法的局限性就是没法使用空格以外的字符进行分割字符串

3.istringstream

istringstream str(" this is a sentence");	
string out;

while (str >> out) {
	cout << out << endl;
}

运行

 this 
 is 
 a 
 sentence

4. getline() 实现 split()

void split(const std::string &s, std::vector<std::string> &elems, char delim = ' ') {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

int main()
{
    string line = "asd fasdf fadf fa";
    vector<string> strs;
    split(line, strs);
    for(auto &s: strs) {
        cout << s << endl;
    }
    return 0;
}

getline函数,顾名思义,是用来获取一行数据的,不过它的第三个参数也可以修改成其他字符,这样就可以将其他字符作为行分割符使用。

不过这种实现的缺点就是,getline每遇到一个行分割符都会返回一次,所以对于分割符连续的情况就束手无策了。

例如:

string str= "dsadsad sdsadasd wwwww eeeee";

打印结果就是:

dsadsad 
sdsadasd 
wwwww 
eeeee
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌宝儿姐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值