请教:如何分隔字符串,存入数组?

gzu120 2006-11-04 05:16:58
字符串char* a[]=" 1 n ADC "
请教,如何实现分隔,把1、n、ABC分别存入数组d[1]、d[2]、d[3]。
我用strtok(),总得不到正解,郁闷-----
谢谢!
...全文
231 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gzu120 2006-11-04
  • 打赏
  • 举报
回复
谢谢
jixingzhong 2006-11-04
  • 打赏
  • 举报
回复
// 从一个字符串中分割子串,然后得到 最长/最短串 ,
// 修改一下, 把分割出来的串 strcpy 保存一下就可以了 ~~

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

int main()
{
char s[] = "We are proud of you";
char max[20]={0},min[10]={0}, tmp[50], *p;
int index=0;
while(index<strlen(s))
{
strcpy(tmp, s);
p = strtok(tmp+index, " ");
index += strlen(p)+1;
if( 0 == strlen(max)) strcpy(max, p);
if( strlen(p) > strlen(max)) strcpy(max, p);

if( 0 == strlen(min)) strcpy(min, p);
if( strlen(p) < strlen(min)) strcpy(min, p);
}
printf("The max-len substring is: %s\n", max);
printf("The min-len substring is: %s\n", min);
system("PAUSE");
return 0;
}
jixingzhong 2006-11-04
  • 打赏
  • 举报
回复
C语言的话,
由于你的分割字符串的空格数目不一致,
所以不好用 ~~

如果你把字符串中间的空格都格式化, 只留下一个空格分割,
那么就好办了 ~
jixingzhong 2006-11-04
  • 打赏
  • 举报
回复
C++ 用 istringstream

stream>>d1>>d2>>d3;
BoXoft 2006-11-04
  • 打赏
  • 举报
回复
设一个状态变量,读到非空格就置一,读到空格就清零并且把保存前面读到的字符。
lann64 2006-11-04
  • 打赏
  • 举报
回复
istringstream stream(a);
stream>>d1>>d2>>d3;
lann64 2006-11-04
  • 打赏
  • 举报
回复
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
char d1[10],d2[10],d3[10];
char *a=" 1 n ADC ";
istringstream stream(a);
stream>>d1;
stream>>d2;
stream>>d3;
cout<<d1<<endl;
cout<<d2<<endl;
cout<<d3<<endl;
}
lw1a2 2006-11-04
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <conio.h>
#include <string.h>

int main(void)
{
char a[]=" 1 n ADC ";
char *p;
char *d[3];
int i=0;
p=strtok(a," ");
d[i]=(char*)malloc(strlen(p)+1);
strcpy(d[i++], p);
while(p=strtok(NULL," "))
{
d[i]=(char*)malloc(strlen(p)+1);
strcpy(d[i++], p);
}

for(i=0; i<3; i++)
{
printf("%s\n", d[i]);
free(d[i]);
}

getch();
return 0;
}

64,654

社区成员

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

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