为啥从sentence[6]开始就录不进去了,

img

img

img


图1为问题,图2为我写的代码,图3为正确代码,我感觉是因为我的i不规则增加导致的

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;
}