字串分割

有時遇到一個字串裡有,*,之類的,例如:"123,456*789",若想要取得456這字串的話,程式碼如下:

std::string GetField(int nIndex)
{
    std::string strTemp("123,456,789");
    int nCurPos = 0;
    int nCurIndex = 0;
    int nLen = strTemp.length();
    while ((nCurPos < nLen) && (nCurIndex < nIndex))
    {
        if ( strTemp[nCurPos] == _T(',') || 
            strTemp[nCurPos] == _T('*') ||
            strTemp[nCurPos] == _T('\r') || 
            strTemp[nCurPos] == _T('\n') )
        {
            nCurIndex ++;
        }
        nCurPos ++ ;
    }

    if (nCurIndex < nIndex )
        return "Error";

    int nFieldStart = nCurPos;

    while (nCurPos < nLen)
    {
        if ( strTemp[nCurPos] == _T(',') || 
            strTemp[nCurPos] == _T('*') ||
            strTemp[nCurPos] == _T('\r') || 
            strTemp[nCurPos] == _T('\n') )
        {
            break;
        }

        nCurPos ++ ;
    }

    return strTemp.substr(nFieldStart, nCurPos - nFieldStart);
}
從別人的程式碼取得的!真是有趣,不過我試著用STL去改寫,但是發現效率會變差許多,例如:

    while (nCurPos < nLen)
    {
        if ( strTemp[nCurPos] == _T(',') || 
            strTemp[nCurPos] == _T('*') ||
            strTemp[nCurPos] == _T('\r') || 
            strTemp[nCurPos] == _T('\n') )
        {
            break;
        }

        nCurPos ++ ;
    }
改成
nCurPos = strTemp.find_first_of(",*\\r\\n", nFieldStart);
我只改這個部分,while的效率比上STL好多了,不過這也是可以理解的啦!

0 意見:

張貼留言