簡體   English   中英

反向字符串列表順序

[英]Reverse string list order

我想顛倒字符串在數組中的存儲順序,以便最后一個在新數組中成為第一個。 到目前為止,我正在獲取數據並將其存儲在第一個數組中,但是我被卡在那里。 我只想顛倒字符串順序,而不是字符串本身。

輸入示例:

here is a sample
line two of test

輸出:

line two of test
here is a sample

到目前為止,我將輸入存儲在第一個數組中:

// Accept user input until hit EOF.
while (( c = getc(stdin) ) != EOF) {
    if(input != NULL) {
        int c = EOF;
        int i = 0;

        // Accept user input until hit EOF.
        while (( c = getc(stdin) ) != EOF) {
            input[i++] = (char)c;
            input[i++] = (char)c;

            // If reached maximize size, realloc size.
            if (c == '\n') {
                input[i]='\0';
            }

            if (i == current_size) {
                current_size = i + len_max;
                input = realloc(input, current_size);
            }
        }

        input[i] = '\0';
    }

假設您有一個char *數組,並且知道該數組的長度:

在數組上循環,然后將位置i的元素與位置n - i - 1的元素交換,其中n是數組的長度。

對於n = 10,您將得到:

i = 0, n - i - 1 = 9
i = 1, n - i - 1 = 8
i = 2, n - i - 1 = 7
i = 3, n - i - 1 = 6
i = 4, n - i - 1 = 5

記住當您達到n / 2時,請停止循環播放。

嘗試存儲在鏈接列表中。 這將是一種更好,更輕松的顛倒順序的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM