2021-10-05 C++反转串的多种方法

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

void reverse1(char *ch, int n)
{
	int low = 0, high = n-1;
	while(low < high)
	{
		swap(ch[low],ch[high]);
		low++;
		high--;
	}
}

void reverse2(char *ch, int n)
{
	for (int i = 0; i < n/2; ++i)
	{
		swap(ch[i],ch[n-1-i]);
	}
}

int reverseNum(int num)
{
	int result = 0;
	while(num)
	{
		result = result * 10 + num % 10;
		num = num / 10;
	}
	return result;
	cout << result;
}

int main(int argc, char const *argv[])
{
    char ch[] = "abcdef";

    cout << "1.原字符串:"<< ch << endl;

    cout << "2.while 循环翻转后:";
	reverse1(ch,strlen(ch));	cout << ch<< endl;

	cout << "3.for 循环又翻转回来后:";
	reverse2(ch,strlen(ch)); 	cout << ch << endl;

	cout << "4.string 的strrev()函数翻转回来:";
	strrev(ch);				 	cout << ch << endl;

	cout << "5.algorithm 的reverse()函数翻转回来:";
	string str = ch;
	reverse(str.begin(), str.end());	cout << str << endl;

	cout << "6.数字翻转123456:";
	int num = 123456;
	cout << reverseNum(num) << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weiabc/article/details/120619118