C++如何进行字符串分割,C++如何按照空格对字符串进行解析,C++如何按照逗号对字符串解析

C++中对字符串进行分割不是像Java一样容易的事情,有下面几种办法:
推荐采用第一种,统一而且能够对逗号等特殊字符做处理

1. 采用istringstream+getline()

代码如下:

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    
    
    std::cout << token << '\n';
}

2. 采用C风格字符串中的strtok

    #include <stdio.h>
    #include <stdlib.h>  
    #include <string.h>
    string str = "dog cat cat dog";
    char *dup = strdup(str.c_str());
    char *token = strtok(dup, " ");
    while (token != NULL) {
    
    
        v.push_back(string(token));
        token = strtok(NULL, " ");
    }
    free(dup);

3. 采用find+substr

代码如下:

	string str = "dog cat cat dog";
    string str2 = str;
    while (str2.find(" ") != string::npos) {
    
    
        int found = str2.find(" ");
        v.push_back(str2.substr(0, found));
        str2 = str2.substr(found + 1);
    }    
    v.push_back(str2);

4. 直接使用stringstream

代码如下:

std::string str = "abc def ghi";
std::stringstream ss(str);

string token;

while (ss >> token)
{
    
    
    printf("%s\n", token.c_str());
}

5. 采用迭代器iterator

代码如下:

    #include <vector>
    #include <iostream>
    #include <string>
    #include <sstream>
    
    string str = "dog cat cat dog";
    istringstream in(str);
    vector<string> v;
    
    #include <iterator>
    copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(v));

推荐采用第一种,统一而且能够对逗号等特殊字符做处理

参考资料:

  1. https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings
  2. https://www.cnblogs.com/grandyang/p/4858559.html

猜你喜欢

转载自blog.csdn.net/Sansipi/article/details/127597697