How do I reverse a C/C++ string using only one buffer?

Asked 2 years ago, Updated 2 years ago, 79 views

I know how to use two buffers How do I reverse a C/C++ string using only one buffer?

for(int i=0; i<strlen(s1); i++)
    s2[strlen(s1)-i-1] = s1[i];

c string c++ reverse

2022-09-22 08:37

1 Answers

It's the shortest and simplest way to write in C++.

#include <algorithm>
std::reverse(str.begin(), str.end());

Use the variable intc temporarily to exchange the front and back values, as in swapping.

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;
    }
}


2022-09-22 08:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.