在翻转句子时,最后一句话没有反转

时间:2014-01-25 09:04:43

标签: c string algorithm

我写了一个程序,它将翻转一个句子并打印出来。

在这段代码中,我得到的所有单词都是正确的,除了最后一个。即在反转代码中的句子后,“hiii”仍然是“iiih”,其余的输出是正确的。

void reverse(char * s, int len){
    int counter = 0;
    int end = len - 1;
    char temp;

    for (counter = 0; counter < len / 2; counter++, end--) {
        temp = s[counter];
        s[counter] = s[end];
        s[end] = temp;
    }
}

int main(void){
    char s[] = "hiii all i want to reverse this sentence so please help me fast";
    int c = 0;
    int len = strlen(s);
    int wl = 0;
    int start = 0;
    printf("\n    s =  %s", s);
    reverse(s, len);

    for (c = 0; c < len; c++){
        if (!wl)
            start = c;

        if (s[c] != ' '){
            wl++;
        }
        else {
            reverse(s + start, wl);
            wl = 0;
        }
    }
    printf("\nnow s =  %s", s);
}

1 个答案:

答案 0 :(得分:6)

字符串中的最后一个单词不是以空格字符结尾。 因此,在 for循环(未经测试)之后你需要这样的

if (wl > 0) {
     reverse(s + start, wl);
}

也可以反转最后一个字。

已添加:完整代码:

int main(void) {
    char s[] = "hiii all i want to reverse this sentence so please help me fast";
    int c = 0;
    int len = strlen(s);
    int wl = 0;
    int start = 0;
    printf("\n    s =  %s", s);
    reverse(s, len);

    for (c = 0; c < len; c++) {
        if (!wl) {
            start = c;
        }

        if (s[c] != ' ') {
            wl++;
        } else {
            reverse(s + start, wl);
            wl = 0;
        }

    }

    if (wl > 0) {
        reverse(s + start, wl);
    }

    printf("\nnow s =  %s", s);

}

输出:

    s =  hiii all i want to reverse this sentence so please help me fast
now s =  fast me help please so sentence this reverse to want i all hiii