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

前端 未结 30 1900
长发绾君心
长发绾君心 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:39

    Yet another:

    #include 
    #include 
    
    int main(int argc, char **argv) {
    
      char *reverse = argv[argc-1];
      char *left = reverse;
      int length = strlen(reverse);
      char *right = reverse+length-1;
      char temp;
    
      while(right-left>=1){
    
        temp=*left;
        *left=*right;
        *right=temp;
        ++left;
        --right;
    
      }
    
      printf("%s\n", reverse);
    
    }
    

提交回复
热议问题