首页 > 代码库 > 字符串逆置

字符串逆置

重视思想和理解原理

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

char* reverseStr(char * str, char * dest, int len)
{
    //指向最后一个字符
    char * s= &str[len-1];
    char *d = dest;

    while(len >= 0)
    {
        *dest++ = *s--;
        len--;
    }

    return d;
}

int main()
{
    char * str = "hello world";
    int len = strlen(str);
    char *dest = (char *)malloc(sizeof(char)*len);

    char* d = reverseStr(str, dest, len);

    cout<<"d==="<<d<<endl;
    return 0;
}

 

字符串逆置