面试经典题目:字符串的反转算法

#include <iostream>

using namespace std;

char *strrev1(const char *str)
{
	int len = strlen(str);
	char *temp = new char[len + 1];
	strcpy(temp, str);

	for (int i = 0; i < len / 2; i++)
	{
		char iTemp = temp[i];
		temp[i] = temp[len - i - 1];
		temp[len - i - 1] = iTemp;
	}
	return temp;
}

char *strrev2(const char *str)
{
	int len = strlen(str);
	char *temp = new char[len + 1];
	strcpy(temp, str);
	char *ret = temp;
	char *p = temp + len - 1;

	while (p > temp)
	{
		//char iTemp = *p;  //方法一
		//*p = *temp;
		//*temp = iTemp;

		//*p ^= *temp;	//方法二
		//*temp ^= *p;
		//*p ^= *temp;

		*p = *p + *temp;
		*temp = *p - *temp;//方法三
		*p = *p - *temp;

		p--;
		temp++;
	}
	return ret;

}

int main(int argc, char *argv[])
{
	char *str = "Hello, I'm a student!";
	char *temp;
	//temp = strrev1(str);
	temp = strrev2(str);
	cout << temp << endl;

	system("pause");
	return 0;
}

你可能感兴趣的:(面试经典题目:字符串的反转算法)