【Windows编程】分割CString字符串

在对szBranches字符串以空格分割时发现分割出来的字符串内存是以'0a'结尾,百度一下发现'0a'代表换行符,请教大佬后发现原因所在~emmmm,实际上这是个很简单很简单的问题,是我zz了……反思了一下出现这低级错误原因,原因之一是我日常犯傻了:),原因之二是被调试时的字符串骗了…调试时发现szBranches字符串为:

由上图所示,一眼看过去感觉他是"11空格12…"形式,但是当将该字符串输出到OutPut窗口是可以清晰看出是以'\n'分割字符串


                                                                              我是分割线,以下是分割字符串部分


要将该字符串分割成11、12、dev1、hh形式方法很简单,首先利用CString自带的remove函数删除字符串的*和空格  

    strSrc.Remove('*');

    strSrc.Remove(' ');

然后以'\n'字符分割字符串最后分割结果装进strResult中。

    strGap = _T('\n')    

    nPos = strSrc.Find(strGap); // 获得‘\n’字符在原字符的索引

   
    while(0 <= nPos)
    {

         CString strLeft = strSrc.Left(nPos); // 获得nPos左边的字符串

         if (!strLeft.IsEmpty())

             strResult.Add(strLeft);

         // 从右边1开始获取从右向左前 nCount个字符
         strSrc = strSrc.Right(strSrc.GetLength() - nPos - 1); 

         nPos = strSrc.Find(strGap);
    }

该完整分割函数如下所示:

void SplitCString(CString strSrc, CString strGap, CStringArray & strResult)
{

    strSrc.Remove('*');

    strSrc.Remove(' ');

    nPos = strSrc.Find(strGap);

    CString strLeft = _T("");

    while(0 <= nPos)
    {

         strLeft = strSrc.Left(nPos);

         if (!strLeft.IsEmpty())

             strResult.Add(strLeft);

         strSrc = strSrc.Right(strSrc.GetLength() - nPos - 1);

         nPos = strSrc.Find(strGap);
    }
}

PS:不要返回CStringArray,好像会出问题,所以这里将返回结果当做引用参数传入

(如果对你有帮助的话麻烦点个赞哟~谢谢dφ(>ω<*) )

猜你喜欢

转载自blog.csdn.net/quellaaa/article/details/81286396