1. 程式人生 > >C++中以固定分隔符分割CString字串

C++中以固定分隔符分割CString字串

CString * SplitString(CString str, char split, int& iSubStrs)
{
    int iPos = 0; //分割符位置
    int iNums = 0; //分割符的總數
    CString strTemp = str;
    CString strRight;
    //先計運算元字串的數量
    while (iPos != -1)
    {
        iPos = strTemp.Find(split);
        if (iPos == -1)
        {
            break;
        }
        strRight = strTemp.Mid(iPos + 1, str.GetLength());
        strTemp = strRight;
        iNums++;
    }
    if (iNums == 0) //沒有找到分割符
    {
        //子字串數就是字串本身
        iSubStrs = 1; 
        return NULL;
    }
    //子字串陣列
    iSubStrs = iNums + 1; //子串的數量 = 分割符數量 + 1
    CString* pStrSplit;
    pStrSplit = new CString[iSubStrs];
    strTemp = str;
    CString strLeft;
    for (int i = 0; i < iNums; i++)
    {
        iPos = strTemp.Find(split);
        //左子串
        strLeft = strTemp.Left(iPos);
        //右子串
        strRight = strTemp.Mid(iPos + 1, strTemp.GetLength());
        strTemp = strRight;
        pStrSplit[i] = strLeft;
    }
    pStrSplit[iNums] = strTemp;
    return pStrSplit;
}