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

如题所述

第1个回答  2022-11-16

程序源码如下:

#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");

}

相似回答