Reverse C-style String? - C ++

I want to use pointers to change a char array in C ++. I was wondering if there is something that I have to do differently? Am I doing it right? Is there a more efficient way to achieve this?

My little program:

int main ( )
{
    char buffer[80];

    PrintHeader();

    cout << "\nString reversal program";
    cout << "\nType in a short string of words.";
    cout << "\nI will reverse them.";
    cout << "\n:";
    cin.getline(buffer, 79);

    cout << "\nYou typed " << buffer;
    reverse (buffer);
    cout << "\nReversed: " << buffer;

    cout << endl;
    system("PAUSE");
    return 0;

}


void reverse(char* string)
{
    char* pStart, *pEnd;
    int length;
    char temp;

    length = strlen(string);

    pStart = string;
    pEnd = &string[length - 1];

    while(pStart < pEnd)
    {
        temp = *pStart;
        *pStart = *pEnd;
        *pEnd = temp;
        pStart++;
        pEnd--;
    }
}
+3
source share
5 answers
void str_reverse( char *str ) {
    char *str_end = strchr( str, 0 );
    std::reverse( str, str_end );
}

if you have to write a loop,

void str_reverse( char *str ) {
    std::size_t len = std::strlen( str );
    for ( std::size_t index = 0; index != len / 2; ++ index ) {
        std::swap( str[ index ], str[ len - index - 1 ] );
    }
}

or, of course, if you can use a C ++ string,

void str_reverse( std::string &str ) {
    std::reverse( str.begin(), str.end() );
}
+9
source

Assuming you can't use anything but C string functions, I would

  • Avoid pre-declaring variables at the beginning of a function. This is a requirement of C (with the 1990 standard), but in C ++ it is more idiomatic to declare and initialize the variables in which you use them.

  • ( ), .

- :

void reverse(char* string)
{
    char* first = string;
    char* last = string + strlen(string);

    while(first < last)
    {
        --last; //avoids decrementing last beyond start of string if string is empty
        char temp = *first;
        *first = *last;
        *last = temp;
        ++first;
    }
}
+3

std::swap(*pStart, *pEnd) .

, std::reverse(buffer, buffer + strlen(buffer)). , , , , .

, , nit: if length==0, &string[length - 1] .

+1

, , , , . .

void RevBuff(char* Buffer)
{

int length = strlen(Buffer);
char * CpBuff = _strdup(Buffer);
for(int i = length -1, x = 0; i >=0 ; i--, x++)
{
    Buffer[x] = CpBuff[i];
}
free(CpBuff);
}

, , , ( , , , , Google, .

0

, , .

( ), , , . , .

, , ( - ), .

, ( , , ), . 50 , .

0

Source: https://habr.com/ru/post/1731314/


All Articles