solution[i] = sentenct[i];
前面的i要连续,跟后面的i要独立出来。
int main()
{
int i = 0, j, k = 0, len;
char sentenct[200] = {0}, solution[200] = {0};
gets(sentenct);
len = strlen(sentenct);
while (i < len)
{
if (sentenct[i] == 32 && sentenct[i + 1 == 32])
{
solution[k++] = sentenct[i];
for (j = i; j < len; j++)
{
if (sentenct[j] != 32)
break;
}
i = j;
}
solution[k++] = sentenct[i];
i++;
}
puts(solution);
return 0;
}
别忘了,循环最后有个i++啊,当i=j时,sentence[j]已经是字符了,再i++的话,就丢失了一个字符了啊。所以应该写成i = j-1
供参考:
#include <stdio.h>
int main()
{
int i = 0, k = 0, flg = 0;
char sentenct[201] = { 0 }, solution[201] = { 0 };
gets(sentenct);
while (sentenct[i])
{
if (sentenct[i] == ' ' && flg == 0){
solution[k++] = sentenct[i];
flg++;
}
if(sentenct[i] != ' '){
solution[k++] = sentenct[i];
flg = 0;
}
i++;
}
solution[k] = '\0';
puts(solution);
return 0;
}