C++字符串分割

2020-04-16  本文已影响0人  退休码农飞伯德

很多人对C++的刻板印象是C++不适合处理字符串,其实C++也是有很方便的函数可以处理字符串的。下面我们来讲一下C++如何来对字符串进行分割。

使用strtok函数

使用strtok函数对字符串进行分割,该函数的声明如下:

char* strtok( char* str, const char* delim );

注意传入的参数是C风格的字符串,头文件为C的字符串库:<cstring>或者<string.h>。

下面是示例代码,示例代码尽可能使用C++风格的字符串,假设输入输出都是C++风格的字符串,因此会涉及到C风格字符串和C++风格字符串的转换:

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
    vector<string> result;
    string str = "A bird came down the walk";
    char *str_cpy = new char[str.size()];
    // convert const char* to char*
    strcpy(str_cpy, str.c_str());
    char *token = strtok(str_cpy, " ");
    while (token != NULL) {
        //cout << token << endl;
        result.push_back(string(token));
        token = strtok(NULL, " ");
    }

    for (auto r: result) {
        cout << r << endl;
    }

    return 0;
}

使用find函数

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

std::vector<std::string> split(const std::string& s, const std::string &delim)
{
    std::vector<std::string> out;
    std::string::size_type beg = 0;
    for (auto end = 0; (end = s.find(delim, end)) != std::string::npos; ++end)
    {
        out.push_back(s.substr(beg, end - beg));
        beg = end + 1;
    }

    out.push_back(s.substr(beg));

    return out;
}

int main()
{
    std::string s = "read[addr=0x17,mask=0xff,val=0x7],read_his[addr=0xff,mask=0xff,val=0x1],read[addr=0xf0,mask=0xff,val=0x80]";
    //const char delim = ']';
    std::string delim = "]";
    std::vector<std::string> out;
    out = split(s, delim);

    for (auto &s: out) {
        std::cout << s << '\n';
    }

    return 0;
}

使用find_first_not_of和find函数

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

void tokenize(std::string const &str, std::string delim,
            std::vector<std::string> &out)
{
    size_t start;
    size_t end = 0;

    while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
    {
        end = str.find(delim, start);
        out.push_back(str.substr(start, end - start));
    }
}

int main()
{
    std::string str = "I love you";
    int pos = str.find_first_not_of(" ");


    std::cout << pos << std::endl;

    return 0;
}

上面这两种方法思路基本一样,都是先查找第一个匹配的字符的位置,然后更新查找范围。

使用C++11正则表达式

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string s = "C*C++*Java";
    std::regex regex("\\*");

    std::vector<std::string> out(
                    std::sregex_token_iterator(s.begin(), s.end(), regex, -1),
                    std::sregex_token_iterator()
                    );

    for (auto &s: out) {
        std::cout << s << '\n';
    }

    return 0;
}

参考资料

  1. https://en.cppreference.com/w/cpp/string/byte/strtok
  2. https://www.techiedelight.com/split-string-cpp-using-delimiter/
  3. https://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of
上一篇 下一篇

猜你喜欢

热点阅读