中文字符的处理
有一行包含字符的中文字符串,如下所示:
CString strTmp("==============测试===================");
我要把'='去掉,用以下语句:
strTmp.Remove('=');
可其中中文就变成了?,这是怎么回事,因该如何操作才能正确的去除'='?
问题点数:30、回复次数:5Top
1 楼huntout(猎手)回复于 2000-07-28 16:17:00 得分 20
下面是Remove的源程序,問題就出在_tcsinc函數上,它的作用是指針向後位移一位,
但pstrDest指向漢字的第一個字節時,_tcsinc(pstrDest)會後移兩位。
int CString::Remove(TCHAR chRemove)
{
CopyBeforeWrite();
LPTSTR pstrSource = m_pchData;
LPTSTR pstrDest = m_pchData;
LPTSTR pstrEnd = m_pchData + GetData()->nDataLength;
while (pstrSource < pstrEnd)
{
if (*pstrSource != chRemove)
{
*pstrDest = *pstrSource;
pstrDest = _tcsinc(pstrDest);
}
pstrSource = _tcsinc(pstrSource);
}
*pstrDest = '\0';
int nCount = pstrSource - pstrDest;
GetData()->nDataLength -= nCount;
return nCount;
}
解決辦法是仿照自己重載一下Remove,考慮一下漢字。
Top
2 楼dyj1999(dyj1999)回复于 2000-07-28 16:23:00 得分 0
汉字不能用Remove,否则连汉字一起移去,若字母就没这个问题Top
3 楼softsprite(软件精灵)回复于 2000-07-28 16:30:00 得分 10
CString strTmp = "=====中文=====";
int i;
while ( (i=strTmp.Find('=')) >= 0 )
{
strTmp.Delete(i);
}
Top
4 楼huntout(猎手)回复于 2000-07-28 16:51:00 得分 0
我以前遇到過這個問題,並曾經用過softsprite的方法,但當字符串很長時,極其耗時,不建議使用。可以用下面的函數,我已調試過︰
void Remove(CString &str, char chRemove)
{
int nLen = str.GetLength();
char* pstr = new char[nLen + 1];
strcpy(pstr, (LPCTSTR)str);
char* pstrSource = pstr;
char* pstrDest = pstr;
char* pstrEnd = pstr + nLen;
while (pstrSource < pstrEnd)
{
if (*pstrSource != chRemove)
{
*pstrDest = *pstrSource;
if (*pstrDest < 0)
{
*(pstrDest+1) = *(pstrSource+1);
}
pstrDest = _tcsinc(pstrDest);
}
pstrSource = _tcsinc(pstrSource);
}
*pstrDest = '\0';
str = pstr;
delete[] pstr;
}
Top
5 楼UserReg(用户注册)回复于 2000-07-28 17:15:00 得分 0
strTmp.Remove('=');
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
改为strTmp.Replace("=","");即可
Top





