编写字符串反转函数的5种方法

#include
#include
#include


char *strrev1(const char *str)
{
int i;
int len = strlen(str);
char *tmp = malloc(sizeof(char) * (len+1));//分配堆内存,多一个字节存放'\0'
if (tmp == NULL)
{
printf("malloc is failed\n");
return NULL;
}

//初始化堆内存为0

memset(tmp, 0, sizeof(len+1));


strcpy(tmp, str);


//遍历字符串,将第一个字符和最后一个交换,第二个和最后第二个交换,依次循环

for(i = 0; i < len/2; i++)
{
char c = tmp[i];
tmp[i] = tmp[len-i-1];
tmp[len-i-1] = c;
}


return tmp;
}


//通过指针交换

char *strrev2(const char *str)
{
char *tmp = malloc(strlen(str)+1);
memset(tmp, 0, (strlen(str)+1));
strcpy(tmp, str);
char *ret = tmp;
char *p = tmp + strlen(str) - 1;


while (p > tmp)
{
char t = *tmp;
*tmp = *p;
*p = t;


--p;
++tmp;
}


return ret;
}


//考虑时间和空间的优化,交换字符串的优化算分,通过异或运算符来交换字符串

char *strrev3(const char *str)
{
char *tmp = malloc(strlen(str)+1);
memset(tmp, 0, (strlen(str)+1));
strcpy(tmp, str);
char *ret = tmp;
char *p = tmp + strlen(str) - 1;


while (p > tmp)
{
*p ^= *tmp;
*tmp ^= *p;
*p ^= *tmp;


--p;
++tmp;
}


return ret;
}



//考虑时间和空间的优化,交换字符串的优化算分,通过数学运算符来交换字符串
char *strrev4(const char *str)
{
char *tmp = malloc(strlen(str)+1);
memset(tmp, 0, (strlen(str)+1));
strcpy(tmp, str);
char *ret = tmp;
char *p = tmp + strlen(str) - 1;


while (p > tmp)
{
*p = *p + *tmp;
*tmp = *p-*tmp;
*p = *p-*tmp;


--p;
++tmp;
}


return ret;

}



char *strrev(const char *str)
{
char *p, *_p;
const char *_str;
int len, i;
if (str == NULL)
{
printf("str == NULL\n");
return NULL;
}


//测试源字符串的长度

len = strlen(str);

//在堆中分配内存,len+1表示为最后一个字节为‘\0’
p = (char*)malloc(sizeof(char)*(len+1));
if (p == NULL)
{
printf("malloc memory is failed\n");
return NULL;
}


_p = p;


//初始化堆内存

memset(p, 0, sizeof(len+1));


//循环到字符的结尾‘\0’处

_str = str;
while (*_str != '\0')
{
 _str++;
}


--_str;

//拷贝字符串操作

for(i = len; i > 0; i--)
{
*p = *_str;
p++;
_str--;
}


//返回堆内存

return _p;
}




int main()
{
char *str = "12878883789546";


printf("str:%s\n", str);
char *_str = strrev4(str);


printf("_str:%s\n", _str);


free(_str);


return EXIT_SUCCESS;
}

























你可能感兴趣的:(c/c++小例子)