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

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

    But I think the XOR swap algorithm is the best...

    char str[]= {"I am doing reverse string"};
    char* pStr = str;
    
    for(int i = 0; i != ((int)strlen(str)-1)/2; i++)
    {
        char b = *(pStr+i);
        *(pStr+i) = *(pStr+strlen(str)-1-i);
        *(pStr+strlen(str)-1-i) = b;
    }
    

提交回复
热议问题