求c语言程序:把输入的字符串中连续的空格转变成单个空格

来源:百度知道 编辑:UC知道 时间:2024/05/28 10:39:13
例如:输入
hello world my name is happy
输出
hello world my name is happy

#include <stdio.h>
main(void)
{
int space=1,i=-1;
char a[80];
gets(a);

while(a[++i]!='\0')
{
if(a[i]==' ') space=0;
else
{
if(space==0)
{ space=1;printf(" ");}
printf("%c",a[i]);
}
}
}

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
char a[100];
gets(a);
int s=1;//s表示处理a[i]前出现的空格,1表示有,0表示没。
for(int i=0;a[i];i++)
{
if(s==0)
{
if(a[i]=' ')s=1;
printf("%c",a[i]);
}
else
if(a[i]!=' ')
{
printf("%c",a[i]);
s=0;
}
}
return 0;
}

两组字符数组的"复制"来实现。

a[100],b[100];//a[100]用来存输入的字符。
for(i=0,j=0,temp=0;i<100;i++)
{ if(a[0]==0) continue;//首字符非空
if(a[i]==0)
{ temp++;
continue;