C語言反轉一行字串單詞範例

2019-10-16 22:09:29

在C語言中,如何編寫反轉一行字串單詞的程式?建立一個原始檔:program_to_reverse_line.c,參考以下實現程式碼 -

#include <stdio.h>
#include <string.h>

int string_length2(char s[]) {
    int i = 0;

    while (s[i] != '\0')
        i++;

    return i;
}

void string_reverse2(char st[]) {
    int i, j, len;
    char ch;

    j = len = string_length2(st) - 1;
    i = 0;

    while (i < j) {
        ch = st[j];
        st[j] = st[i];
        st[i] = ch;
        i++;
        j--;
    }
}

int main(void) {
    char line[] = "Yiibai tutorials is one of the best IT tutorials stie in the world.";
    char reverse[100] = "", temp[50];
    int i, j, n;


    n = string_length2(line);

    for (i = n - 1; i >= 0; --i) {

        for (j = 0; i >= 0 && line[i] != ' '; --i, ++j)
            temp[j] = line[i];

        temp[j] = '\0';

        string_reverse2(temp);

        strcat(reverse, temp);
        strcat(reverse, " ");
    }

    printf("Original - %s\n", line);
    printf("Reversed - %s\n", reverse);

    return 0;
}

執行上面範例程式碼,得到以下結果 -

Original - Yiibai tutorials is one of the best IT tutorials stie in the world.
Reversed - world. the in stie tutorials IT best the of one is tutorials Yiibai