先统计字符串的长度,然后根据要截取的长度,对字符串截取,以下代码是网上找的,仅供参考。
CString LeftToChar(CString sSource, int nLength, int nPos,int &nBack)
{
int nSize= sSource.GetLength();
if((!nSize) || (nPos > nSize) || (nPos < 0))
return "";
char *sNewBuffer = new char[nSize];
LPSTR sTempPtr = sNewBuffer;
char sCharbuf[255];
//以防止将一半汉字分为两行
unsigned short nHalfChinese = 0;
int i = nPos;
while((i<nSize) && (i-nPos<nLength))
{
*sTempPtr = sSource.GetAt(i);
//大于0xa1的字节为汉字字节
if((unsigned char)*sTempPtr >= 0xa1)
nHalfChinese ++;
sCharbuf[i-nPos] = *sTempPtr ++;
i++;
}
if (nHalfChinese%2 == 1)
{
sCharbuf[i-nPos-1] = '/0';
nBack = -1;
}
else
{
sCharbuf[i-nPos] = '/0';
nBack = 0;
}
CString ss;
ss.Format("%s",sCharbuf);
if(sNewBuffer != NULL)
{
delete[] sNewBuffer;
sNewBuffer = NULL;
}
return ss;
}
//调用方法:
int nBack;
CString sSource;
sSource = "张学d有要在要一人有工人了以要";
CString test = LeftToChar(sSource, 19, 0, nBack);
AfxMessageBox(test);