簡體   English   中英

嘗試創建一個 C 程序,逐字查找字符串的反轉

[英]Trying to create a C program that finds the reverse of a string word by word

所以在這里我真的不知道為什么它不起作用,當我嘗試輸入hello world時,我得到了結果:woll dlrl,我不知道為什么,請幫助......我認為問題與相關的事情有關到 \0 或我沒有注意或我根本不知道的東西,該程序可以正常工作,但它沒有給我我想要的東西

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

int main() {

  char S[250] = {};
  char arr_R[250] = {};
  int start = 0, end = 0, space_loc = 0; // start represents the starting index
                                         // of a word in the string , similar
                                         // thing goes for end .

  // space_loc determines the index when the program finds a space of a \0 to
  // try sperate words.
  gets(S);

  for (int i = 0; i < 250; i++) { // it won't actually go for 250 times loop ,
                                  // the program will end when it sees '\0'

    if (S[i] == ' ') {

      space_loc = i;
      end = i - 1;
      for (int j = 0; j <= (end - start) + 1; j++) {
        arr_R[j] = S[end];
        end--;

        printf("%c", arr_R[j]);
      }

      strcpy(arr_R, ""); // here i am emptying the string arr_R but i dont think
                         // it's necessary at all since the overwriting and
                         // printing process will iterate over (end-start)+1
                         // which represents the new word that the program
                         // reversed and copied to arr_R
      printf("%c", S[space_loc]); // just printing the space
      start = space_loc + 1;
    }

    if (S[i] == '\0') {

      space_loc = i;
      end = i - 1;
      for (int j = 0; j <= (end - start) + 1; j++) {
        arr_R[j] = S[end];
        end--;
        printf("%c", arr_R[j]);
      }

      strcpy(arr_R, "");
      printf("%c", S[space_loc]);
      return 0;
    }
  }
}

試試這個版本:我基本上通過重新組合' ''\0'的測試來刪除重復的代碼,刪除了錯誤和無用的 arr_R 刷新,並進行了一些其他的裝飾性更改,用while循環替換for循環。

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

int main() {

    char S[250] = {};
    char arr_R[250] = {};
    int start = 0, end = 0, i=0, j, space_loc = 0, isEnd = 0;
    
    scanf ("%[^\n]%*c", S);
    while (!isEnd)
    {
        isEnd = S[i] == '\0';
        if (S[i] == ' ' || isEnd) 
        {
            space_loc = i;
            end = i - 1;
            j = 0;
            while (end >= start) {
                arr_R[j] = S[end--];
                printf("%c", arr_R[j]);
                j++;
            }
            start = space_loc + 1;
            
            if (isEnd) printf("\n");
            else printf("%c", S[space_loc]);
            
        }
        i++;
    }
    return 0;
}

Output 用“hello world”測試時:

olleH dlrow

暫無
暫無

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

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