65,211
社区成员
发帖
与我相关
我的任务
分享
int W2C(const wchar_t *pw , char *pc,int len)
{
while(len>0)
{
*pc++ = *pw >>8 ;
*pc++ = *pw ;
pw++;
len=len-2;
}
return 0 ;
}
#include <iostream>
#include <string>
using namespace std;
/**
* @brief 字符串替换
* @param[in,out] strBig 源字符串(GBK编码)
* @param[in] strsrc 将被替换的字符串(GBK编码)
* @param[in] strdst 替换后的新字符串(GBK编码)
* @note 汉字占两个字节,直接使用find,有可能匹配两个汉字的高低字节,造成错误~
*/
void string_replace(string & strBig, const string & strsrc, const string &strdst)
{
string::size_type pos=0;
string::size_type srclen=strsrc.size();
string::size_type dstlen=strdst.size();
while( pos+srclen <= strBig.size() )
{
if( strBig.compare(pos, srclen, strsrc) )
{
pos += strBig[pos] < 0 ? 2 : 1;
}
else
{
strBig.replace(pos, srclen, strdst);
pos += dstlen;
}
}
}
int main()
{
string str1 = "这是一个含,的测试例子,测试replace是否正常!";
unsigned char buffer[]={0xa3,0xac,0xa3,0xa5,0xa5,0xa3,0xac,0x85,0x41,0x00};
string str2 = (const char *)buffer;
cout<<"Before replace:"<<endl
<<"str1="<<str1<<endl<<"str2="<<str2<<endl<<endl;
string_replace(str1, ",", " ");
string_replace(str2, ",", " ");
cout<<"After replace:"<<endl
<<"str1="<<str1<<endl<<"str2="<<str2<<endl<<endl;
return 0;
}