hee*_*een 18

这是我使用的perl风格的分割功能:

void split(const string& str, const string& delimiters , vector<string>& tokens)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在搜索中出现的旧线程.我会将`split`的签名更改为没有第三个参数,而返回`vector <string>`(`tokens`将是一个局部变量). (2认同)

Mar*_*ote 11

在C++中没有内置的方法来分割字符串,但是boost提供字符串算法库来执行所有类型的字符串操作,包括字符串拆分.


MSa*_*ers 10

是的,串流.

std::istringstream oss(std::string("This is a test string"));
std::string word;
while(oss >> word) {
    std::cout << "[" << word << "] ";
}
Run Code Online (Sandbox Code Playgroud)

  • 这是我的工作分割器.如果你想在分隔符上拆分,你可以用`getline(oss,word,':')替换`oss >> word`. (3认同)

str*_*ger 7

STL字符串

您可以使用字符串迭代器来完成您的脏工作.

std::string str = "hello world";

std::string::const_iterator pos = std::find(string.begin(), string.end(), ' '); // Split at ' '.

std::string left(str.begin(), pos);
std::string right(pos + 1, str.end());

// Echoes "hello|world".
std::cout << left << "|" << right << std::endl;
Run Code Online (Sandbox Code Playgroud)


str*_*ger -2

C 字符串

\0只需在您想要拆分的位置插入一个即可。这与标准 C 函数所能获得的内置函数差不多。

此函数在第一次出现char分隔符时进行拆分,返回第二个字符串。

char *split_string(char *str, char separator) {
    char *second = strchr(str, separator);
    if(second == NULL)
        return NULL;

    *second = '\0';
    ++second;
    return second;
}
Run Code Online (Sandbox Code Playgroud)