How do you reverse a string in place in C or C++?

前端 未结 30 1899
长发绾君心
长发绾君心 2020-11-22 00:37

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

30条回答
  •  情歌与酒
    2020-11-22 01:27

    Non-evil C, assuming the common case where the string is a null-terminated char array:

    #include 
    #include 
    
    /* PRE: str must be either NULL or a pointer to a 
     * (possibly empty) null-terminated string. */
    void strrev(char *str) {
      char temp, *end_ptr;
    
      /* If str is NULL or empty, do nothing */
      if( str == NULL || !(*str) )
        return;
    
      end_ptr = str + strlen(str) - 1;
    
      /* Swap the chars */
      while( end_ptr > str ) {
        temp = *str;
        *str = *end_ptr;
        *end_ptr = temp;
        str++;
        end_ptr--;
      }
    }
    

提交回复
热议问题