C语言中输入字符串,里面有空格,怎么根据空格把字符串分开,并存在数组里?

如题所述

程序源码如下:

#include<stdio.h>

#include<string.h>

int main(void)

{

char str[1000];//定义一个字符串数组

char strnew[1000];//定义一个备用字符串数组

char m[] = " ";//定义空格变量

printf("请输入一串字符:");//文字提示输入字符串

gets(str);//输入字符串

char *p = strtok(str,m);//取str与m的指针

printf("%s\n",p);  //输出

p = strtok(NULL,m); 

while(p)  //遍历输出

{       

printf("%s\n",p); //输出字符串

p = strtok(NULL,m);  //指向下一个

}

}

程序输出结果:


扩展资料:

C语言:输入一个字符串放入数组里,删除其中的空格

#include <stdio.h>

#include<string.h>

#define N 100

void main()                   

{

int i=0,j;

char c,str[N];

printf("输入字符串str:\n");

while((c=getchar())!='\n')

{

str[i]=c;//输入字符串

i++;

}

str[i]='\0'; 

for(i=0;str[i]!='\0';i++)

{

 if(str[i]==' ')

{

for(j=i+1;str[j]!='\0';j++)

{

str[j-1]=str[j];    

}

str[j]='\0';

}

else continue;

}

str[i-2]='\0';

printf("去掉空格后的字符串为:\n");

for(i=0;str[i]!='\0';i++)

printf("%c",str[i]);

printf("\n");

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-26

给你一个程序,你看看吧

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

int main(void)
{
char a[1000];
char aa[1000];
char c[] = " ";
printf("请输入一串字符:");
gets(a);





char *p = strtok(a,c);
printf("%s\n",p);
p = strtok(NULL,c);
while(p)
{
printf("%s\n",p);
p = strtok(NULL,c); 
}



}

本回答被提问者采纳
第2个回答  2013-09-27
string str = "abc def ghi";
unsigned char i ,j,k;
char fstr[3][4];
j = 0;
k = 0;
for(i = 0; i < 11; i++){
if(str [i] == " "){
j++;
k=0;
}
else{
fstr[j][k] =str [i];
k++;
}
}
for(i = 0; i < 3; i++){
fstr[i][3] = "\0" ;
}

这段代码大约能完成功能吧,有现有的函数可以用的,一时想不起来,好久没用C了。本回答被网友采纳
第3个回答  2013-09-27
刚看到第一眼,就想到一个笨方法应该可行

根据空格算出要分几个数组存放。。并。。。建立对吧。
然后遍历数组呗
遇到空格就存放到另一个数组里面。。。
碰到0 就结束。。。额。。。
第4个回答  2013-09-27
strtok + strcat基本就解决了

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网