VC中实现类似VB的函数Left,Right,Mid,Len(GetCharNum);具体实现代码如下(本代码在WINDOWS XP +VC++6.0下通过):
//取得字符左边字符(实现VB中的Left)
CString Left(CString strInfo, int iNum)
{
CString infotmp=_T("-1");
if(iNum<=0 || strInfo.IsEmpty())
return infotmp;
int cnums=0;//字符数
int lnums=0;//字符长度
int a=0;
while(strInfo.GetLength()>lnums)
{
char c=strInfo.GetAt(lnums);
if (c<0 || c>255) //是中文
{
a=2;
}
else
{
a=1;
}
cnums++;
lnums+=a;
if (cnums==iNum)
{
break;
}
}
infotmp=strInfo.Left(lnums);
return infotmp;
}
//取得字符右边字符(实现VB中的Right)
CString Right(CString strInfo, int iNum)
{
CString infotmp=_T("-1");
if(iNum<=0 || strInfo.IsEmpty())
return infotmp;
int cnums=0;//字符数
int lnums=strInfo.GetLength();//字符长度
int a=0;
int inums=0;
while(lnums>=0)
{
char c=strInfo.GetAt(lnums-1);
if (c<0 || c>255) //是中文
{
a=2;
}
else
{
a=1;
}
cnums++;
lnums-=a;
inums+=a;
if (cnums==iNum)
{
break;
}
}
infotmp=strInfo.Right(inums);
return infotmp;
}
//实现VB中的Mid(不区分英文字符及汉字UNICODE)
CString Mid(CString strInfo, int iPos, int iNum)
{
CString sValue=_T("-1");
//判断是否为错
if(iPos<=0 || iNum<=0 || strInfo.IsEmpty())
return sValue;
//
CString sValuetmp;
sValuetmp=Right(strInfo,GetCharNum(strInfo)-iPos+1);//
sValue=Left(sValuetmp,iNum);
return sValue;
}
//获得字符个数(实现VB中的Len)
int GetCharNum(CString strInfo)
{
CString infotmp;
int cnums=0;
int enums=0;
int nums,a;
infotmp=strInfo;
while(infotmp.GetLength()>0)
{
if(infotmp!=_T("") || infotmp!=NULL)
{
char c=infotmp.GetAt(infotmp.GetLength()-1);
if (c<0 || c>255) //是中文
{
cnums++;
a=2;
}
else
{
enums++;
a=1;
}
infotmp=infotmp.Left(infotmp.GetLength()-a);
}else
break;
}
nums=cnums+enums;
return nums;
}
时间仓促,仅实现功能,未加任何容错处理;不足之处,欢迎相互交流。
email:airen3339@126.com
QQ:34596561 312337667
MSN:airen3339@hotmail.com
2008-6-23(依星)