把一个字符串按某字符(分隔符)分开,如何分最好?

cnxfmz 2011-06-18 04:15:01

wchar_t str[] = L"111,22222";
wchar_t strX[10] = {0};
wchar_t strY[10] = {0};

int strLen = wcslen(str);
int i = 0;
for(; i < strLen; i++)
{
if( str[i] == L',')
{
strX[i] = L'\0';
break;
}
strX[i] = str[i];
}

int j = i + 1;
int n =0;
for(; j < strLen; j++)
{
strY[n] = str[j];
n++;
}

wcout << str << endl;
wcout << strX << endl;
wcout << strY << endl;


只会这个笨办法,还有更方便的吗?
...全文
498 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ryfdizuo 2011-06-18
  • 打赏
  • 举报
回复
stl中的istringstream, ostringstream只能分割空格
strtok可以自己设置token。
sscanf格式要求比较死。
  • 打赏
  • 举报
回复
给你个例子

/* STRTOK.C: In this program, a loop uses strtok
* to print all the tokens (separated by commas
* or blanks) in the string named "string".
*/

#include <string.h>
#include <stdio.h>

char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;

void main( void )
{
printf( "%s\n\nTokens:\n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}


result

A string of ,,tokens
and some more tokens

Tokens:
A
string
of
tokens
and
some
more
tokens
就想叫yoko 2011-06-18
  • 打赏
  • 举报
回复
sscanf
strtok
hustbingdian 2011-06-18
  • 打赏
  • 举报
回复
可以用下stl中的ostream_iterator

64,680

社区成员

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

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