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

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

    Read Kernighan and Ritchie

    #include 
    
    void reverse(char s[])
    {
        int length = strlen(s) ;
        int c, i, j;
    
        for (i = 0, j = length - 1; i < j; i++, j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    }
    

提交回复
热议问题