从字符串中取出字符的问题

来源:百度知道 编辑:UC知道 时间:2024/06/22 07:53:05
a,b是两个CString类型的字符串,
运行a.Format("%s",b[1])时总是出错
CString类重载的[]函数返回的是一个字符,还是字符在字符串中位置的指针?
如何从一个字符串中取出一个字符赋值给另一个字符串?
好几天了,用了几种方法都不行,再把问题说一遍吧,CString类的两个字符串a,b。其中a里边存储的是中文,b是个空串,如何将a中的第i个汉字存储到b中。

如果都是汉字的话可以这么取
b = a.Mid((i-1) * 2,2);

汉字的话牵涉到汉字编码的问题。如果是GB2312的话可以试试下面两个函数:
=========================
//统计字符串S的长度。包含汉字
unsigned int GetStringCount(const std::string &s)
{
short ch;
unsigned cnt = s.size();
for(size_t i=0; i<s.size(); ++i)
{
ch = s.at(i);
if(ch&0x1000) ++i,--cnt;
}
return cnt;
}

//取字符串S从index开始的子串(一字符)
std::string GetString(std::string &s, size_t index)
{
short ch;
std::string res;
unsigned cnt = index;
for(size_t i=0; i<s.size() && i<cnt; ++i)
{
ch = s.at(i);
if(ch&0x1000) ++i,++cnt;
}
ch = s.at(i);
if(ch&0x1000) res=s.substr(i,2);
else res=s.substr(i,1);
return res;
}

如果你是想取一个“字符”赋给另一个字符串,你为什么要写 %s而不是%c呢。。。

a.Format("%s",&b[1])

CString是个类,别那样用,一般的操作都有相应的成员函数的!
b[1]改为b.GetAt(1);