當前位置:編程學習大全網 - 源碼下載 - C語言中輸入字符串,裏面有空格,怎麽根據空格把字符串分開,並存在數組裏?

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

}

  • 上一篇:macd指標詳解?
  • 下一篇:殺毒軟件那個好
  • copyright 2024編程學習大全網