Reverse the ordering of words in a string

后端 未结 30 4189
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 11:12

    I know there are several correct answers. Here is the one in C that I came up with. This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.

    #include
    
    char * strRev(char *str, char tok)
    {
       int len = 0, i;
       char *temp = str;
       char swap;
    
       while(*temp != tok && *temp != '\0') {
          len++; temp++;
       }   
       len--;
    
       for(i = 0; i < len/2; i++) {
          swap = str[i];
          str[i] = str[len - i]; 
          str[len - i] = swap;
       }   
    
       // Return pointer to the next token.
       return str + len + 1;
    }
    
    int main(void)
    {
       char a[] = "Reverse this string.";
       char *temp = a;
    
       if (a == NULL)
          return -1; 
    
       // Reverse whole string character by character.
       strRev(a, '\0');
    
       // Reverse every word in the string again.
       while(1) {
          temp = strRev(temp, ' ');
          if (*temp == '\0')
             break;
    
          temp++;
       }   
       printf("Reversed string: %s\n", a); 
       return 0;
    }
    

提交回复
热议问题