字符串分割

废话不多说,直接上代码:

list<string> Split(const string& _szBeProcessed, const string& _szSeparator)
{
    list<string> liRst;
    if (_szBeProcessed.empty() || _szSeparator.empty())throw "Param 1 or param 2 is empty. Can't processed.";

    // Begin process
    int nSeparatorCurrentIndex = 0;
    int nSeparatorLastIndex = 0;
    while ((nSeparatorCurrentIndex = _szBeProcessed.find(_szSeparator, nSeparatorCurrentIndex)) >= 0)
    {
        liRst.push_back(_szBeProcessed.substr(nSeparatorLastIndex, nSeparatorCurrentIndex - nSeparatorLastIndex));
        nSeparatorLastIndex = ++nSeparatorCurrentIndex;
    }
  if(nSeparatorLastIndex < _szBeProcessed.length())
    liRst.push_back(_szBeProcessed.substr(nSeparatorLastIndex));
return liRst;
}
// Test
list<string> liSplit = Split("hello world. HELLO WORLD.", " ");
    for (string sz : liSplit)
        cout << sz << endl;

// Output result:
hello
world.
HELLO
WORLD.

步骤:

1、遍历分隔符所在的位置。

2、copy从上一分隔符所在位置到当前所在位置。

3、当前位置加一操作,并赋值给上一位置。

4、重复1-3步骤,直到find返回-1。

5、检查上一位置是否小于被处理字符串的长度。是:则表示后边还有待处理的字符串,执行步骤6;否则表示已经到字符串末尾。

6、copy从上一位置到待处理字符串末尾。

原文地址:https://www.cnblogs.com/LandyTan/p/10527335.html