用C语言编写一段程序:删除字符串中的空格,并将原空格后首字母改写为大写字母。

2024-12-12 16:29:16
推荐回答(5个)
回答1:

int main(int argc, char* argv[])
{
char str[] = "Whatever with the past has gone, the best is always yet to come.";

char *p = str;
char *p1 = str;
bool is_space = false; //用于标记上一个字符是否为空格

char ch;
while ( (ch = *p++) != '\0')
{
if (ch == ' ') //如果ch为空格
{
is_space = true;
continue; //结束本次循环,进入下一次循环
}

if (is_space) //如果上一个字为空格
{
is_space = false; //清除空格标记
ch = (ch >= 'a' && ch <= 'z' ? ch - 32 : ch); //判断ch是否为小写字母,并将其转换为大写字母
}

*p1++ = ch;
}

*p1 = '\0'; //末尾加结束符

printf("%s\n", str);

return 0;
}

回答2:

#include
#include
#include
char* delspace(char* str)
{
int l=strlen(str);
int f=0;
char* ps=(char*)malloc(l+1);
char* ps1,*ps2;
ps1=str;
ps2=ps;
while(*str)
{
if(*str==' ')
{
str++;
f=1;
continue;
}
if(f==1)
{
f=0;
if('z'>=*str&&*str>='a')
{
*str=*str-('a'-'A');
}
}
*ps++=*str++;
}
*ps=0;
strcpy(ps1,ps2);
free(ps2);
return ps1;
}

int main()
{
char str[200];
printf("输入字符串:");
gets(str);
puts(delspace(str));
return 0;
}

回答3:

#include
#include
#include
int main()
{
char str[200];
printf("输入字符串:");
int l=strlen(str);
int f=0;
char* ps=(char*)malloc(l+1);
char* ps1,*ps2;
a=str;
b=ps;
while(*str)
{
if(*str==' ')
{
str++;
f=1;
continue;
}
if(f==1)
{
f=0;
if('z'>=*str&&*str>='a')
{
*str=*str-('a'-'A');
}
}
*ps++=*str++;
}
*ps=0;
strcpy(a,b);
free(b);
return a;
return 0;
}

回答4:

#include
int main()
{
char c[40];
int m,n,i,j,k=0;
printf("请输入字符串\n");
gets(c);
n=strlen(c);
for(i=0;i<=n;i++)
{
if(c[i]==' ') {for(m=i;m if(c[i]!=' '&&k) {c[i]-=32;k=0;}
if(c[i]!=' ')printf("%c",c[i]);
}
return 0;
}

回答5:

#include
#include

int main(void)
{
int i;
char str[128];

printf("please input the sentence: \n");
gets(str);

for(i = 0; str[i] != '\0'; i++)
{
if(str[i] == ' ')
{
printf("%c", str[i + 1] - 32);
i++;
}
else
{
printf("%c", str[i]);
}
}

printf("\n");

return 0;
}