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

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

    It's been a while and I don't remember which book taught me this algorithm, but I thought it was quite ingenious and simple to understand:

    char input[] = "moc.wolfrevokcats";
    
    int length = strlen(input);
    int last_pos = length-1;
    for(int i = 0; i < length/2; i++)
    {
        char tmp = input[i];
        input[i] = input[last_pos - i];
        input[last_pos - i] = tmp;
    }
    
    printf("%s\n", input);
    

提交回复
热议问题