当前位置:编程学习 > C/C++ >>

字符串的反转五种方法

#include<iostream>
#include<string>
using namespace std;

char *reverse1(  char *str, int len)
{
    if(len<=1)       //边界条件
		return str;
	char temp = *str;
	*str = *(str+len-1);
	*(str+len-1) = temp;
    return (reverse1( str+1, len-2)-1);
}

char *reverse2( const char *str)
{
    char *temp = new char[strlen(str)+1];
	strcpy(temp, str);    //会复制\0
	int len = strlen(str);
	for( int i=0; i<len/2; i++)
	{
		char ch = temp[i];
		temp[i] = temp[len-i-1];
		temp[len-i-1] = ch;
	}
//	temp[len] = '\0';
	return temp;
}

char *reverse3( const char *str)
{
	char *temp = new char[strlen(str)+1];
	strcpy(temp, str);
	int len = strlen(str);
	char *head = temp;
	char *rear = temp+len-1;
	while(head<rear)
	{
        char ch = *head;
		*head = *rear;
		*rear = ch;
		++head;
        --rear;
	}
//	temp[len] = '\0';
	return temp;
}

char *reverse4( const char *str)
{
	char *temp = new char[strlen(str)+1];
	strcpy(temp, str);
	int len = strlen(str);
	char *head = temp;
	char *rear = temp+len-1;
	while(head<rear)
	{
        *head = *head+*rear;
		*rear = *head-*rear;
		*head = *head-*rear;
		++head;
        --rear;
	}
	return temp;
}

char *reverse5( const char *str)
{
    char *temp = new char[strlen(str)+1];
	strcpy(temp, str);
	int len = strlen(str);
	char *head = temp;
	char *rear = temp+len-1;
	while(head<rear)
	{
		*head^=*rear;
		*rear^=*head;
		*head^=*rear;
		++head;
		--rear;
	}
	return temp;
}
int main()
{   
	char str[7] = "123456";
	cout<<reverse2(str)<<endl;
	cout<<reverse3(str)<<endl;
	cout<<reverse4(str)<<endl;
	cout<<reverse5(str)<<endl;
	cout<<reverse1(str, 6)<<endl;
    return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,