This question already has answers here:
Reverse the ordering of words in a string
                                
                                    (47个答案)
                                
                        
                                5年前关闭。
            
                    
我需要一个程序来反转字符串中的单词。


  输入:我的车快
  输出:快就是车我的


int printRword(char * line) {
    for(; *line; line++) {
        if(*line == ' ') {
            printRword(line + 1);
            printf("%s", line);
            return 0; // after you find the space set it to null
        }
    }
}

int main(void) {
    char *line = "this is a long line that we are working with\n";
    printf("%s", line);
    printRword(line);

    return 0;
}


我知道我需要在找到空格后将其设置为null,并且我尝试了printRword(line + 1)='\ 0';
那是行不通的
有什么建议么?

最佳答案

查找修改后的工作代码:

int printRword(字符*行)

{

   char tempbuf[100]; //Here length i have hardcoded to 100

   char *ptr;
   strcpy(tempbuf,line); //copied to tempbuf to keep the original string unmodified

   //Replace the \n with the null character
    ptr = strrchr(tempbuf,'\n');
    if(ptr != NULL)
    {
      *ptr = '\0';
    }

    while(*tempbuf != '\0')
    {
        ptr = strrchr(tempbuf,' ');
        if(NULL != ptr)
        {
             *ptr = '\0';
              ptr++;

              printf("%s ",ptr);
         }
         else
         {
             printf("%s\n",tempbuf);
             *tempbuf ='\0';
          }
    }


}

测试结果:

atharv @ atharv-Inspiron-5423:〜/ Programming $ ./a.out

这是我们正在处理的一长串

与工作,我们那条线长是这个

atharv @ atharv-Inspiron-5423:〜/编程

关于c - 反转字符串中的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22310904/

10-09 09:00