String in reverse function - c language

There are two ideas, one is to apply an auxiliary space, and then reverse the original string copied to a secondary space, and then output;

Another is to place in reverse order , no additional auxiliary space, the method is the string end to the exchange.

#include <stdio.h>
#include <string.h>
char* str_reverse(char* str)   //字符指针
{
    int n = strlen(str) / 2;
    int i = 0;
    char tmp = 0;
    for (i = 0; i < n; i++)
    {
        tmp = str[i];
        str[i] = str[strlen(str) - i - 1];   //对调
        str[strlen(str) - i - 1] = tmp;     
    }
    return str;
}
int main ()
{
    char s[] = "hello world!";
    printf("str_reverse(s) = %s\n", str_reverse(s));
    return 0;
}

Or the pointer characteristic parameters directly, as follows:

#include <stdio.h>
#include <string.h>
void str_reverse(char* str)   //字符指针
{
    int n = strlen(str) / 2;
    int i = 0;
    char tmp = 0;
    for (i = 0; i < n; i++)
    {
        tmp = str[i];
        str[i] = str[strlen(str) - i - 1];   //对调
        str[strlen(str) - i - 1] = tmp;     
    }
    return str;
}
int main ()
{
    char s[] = "hello world!";
    str_reverse(s);
    printf("str_reverse(s) = %s\n",s );
    return 0;
}

from: https://www.cnblogs.com/lvonve/

 

Guess you like

Origin www.cnblogs.com/imhuanxi/p/11779785.html