请教wstring的字符插入问题。。

xychzh 2010-07-29 07:54:15
wstring wStr = L"一二三四五六七";

我想在“四”的后面插入一个字符'a',怎么操作???


PS:wstring的资料真少
...全文
331 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangweiit 2010-07-29
  • 打赏
  • 举报
回复
ws.insert(ws.find(L'一') + 1,1,'a');
zhangweiit 2010-07-29
  • 打赏
  • 举报
回复
这样可以:

#include <iostream>
#include <string>
#include <stdio.h>
#include <locale.h>
using namespace std;

string& ws2s(wstring &ws, string &str)
{
char *pch = (char *)malloc(ws.length() * 2 + 1);
const wchar_t *pwch = ws.c_str();
wcstombs(pch,pwch,ws.length() * 2);
str.clear();
str.append(pch);
return str;

}
int main()
{

setlocale(LC_ALL,"chs");

wstring ws = L"一二三";
ws.insert(ws.find(L'一') + 1,1,'a');
string s;
ws2s(ws,s);

cout<<s<<endl;

getchar();
return 0;
}
横云断岭 2010-07-29
  • 打赏
  • 举报
回复
真不知道LZ想干啥。
想在wstring 中插入一个字节的字符?

看下内存:

std::wcout.imbue(std::locale("CHS"));

wstring wStr = L"a一二三四五六七bc";
wstring::iterator iter = wStr.begin() + 3;
wStr.insert(iter, 'a');

for (int i = 0;i<wStr.size();++i)
{
int x = (int)&wStr[i];
cout<<x;
wcout<<wStr[i]<<' ';
cout<<endl;
}

zhangweiit 2010-07-29
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 hengyunabc 的回复:]

不知道LZ是什么意思……

[/Quote]
楼主的意思是要在 wstring中插入一个字符
横云断岭 2010-07-29
  • 打赏
  • 举报
回复
不知道LZ是什么意思……


std::wcout.imbue(std::locale("CHS"));

wstring wStr = L"一二三四五六七";
wstring::iterator iter = wStr.begin() + 3;
wStr.insert(iter, L'a');

for (int i = 0;i<wStr.size();++i)
{
wcout<<wStr[i]<<' ';
}

zhangweiit 2010-07-29
  • 打赏
  • 举报
回复
string str = ws2s(wStr);
str.insert(str.find("四"), 1, 'a');

其实这个思路也可以啊

然后,再s2ws

xychzh 2010-07-29
  • 打赏
  • 举报
回复
我问的是wstring
  • 打赏
  • 举报
回复
string str = ws2s(wStr);
str.insert(str.find("四"), 1, 'a');
xychzh 2010-07-29
  • 打赏
  • 举报
回复
问题解决了:

wstring wStr = L"一二三四五六七";
wstring::iterator iter = wStr.begin() + 3;
wStr.insert(iter, 'a');

string str = ws2s(wStr); // wstring转string
cout << str << endl;


有更好的方法,跟上吧,

64,671

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧