[C++] string反转的5种方法

Different methods to reverse a string in C/C++

Given a string, write a C/C++ program to reverse it.

1. Write own reverse function by swapping characters:

One simple solution is to write our own reverse function to reverse a string in C++

// A Simple C++ program to reverse a string 
#include <bits/stdc++.h> 
using namespace std; 

// Function to reverse a string 
void reverseStr(string& str) 
{ 
	int n = str.length(); 

	// Swap character starting from two 
	// corners 
	for (int i = 0; i < n / 2; i++) 
		swap(str[i], str[n - i - 1]); 
} 

// Driver program 
int main() 
{ 
	string str = "geeksforgeeks"; 
	reverseStr(str); 
	cout << str; 
	return 0; 
} 

2. Using inbuilt “reverse” function:

There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.

// A quickly written program for reversing a string 
// using reverse() 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
	string str = "geeksforgeeks"; 

	// Reverse str[begin..end] 
	reverse(str.begin(), str.end()); 

	cout << str; 
	return 0; 
} 

3. Only printing reverse:

// C++ program to print reverse of a string 
#include <bits/stdc++.h> 
using namespace std; 

// Function to reverse a string 
void reverse(string str) 
{ 
for (int i=str.length()-1; i>=0; i--) 
	cout << str[i]; 
} 

// Driver code 
int main(void) 
{ 
	string s = "GeeksforGeeks"; 
	reverse(s); 
	return (0); 
} 

4. Getting reverse of a const string:

// C++ program to get reverse of a const string 
#include <bits/stdc++.h> 
using namespace std; 

// Function to reverse string and return 
// reverse string pointer of that 
char* reverseConstString(char const* str) 
{ 
	// find length of string 
	int n = strlen(str); 

	// create a dynamic pointer char array 
	char *rev = new char[n+1]; 

	// copy of string to ptr array 
	strcpy(rev, str); 

	// Swap character starting from two 
	// corners 
	for (int i=0, j=n-1; i<j; i++,j--) 
		swap(rev[i], rev[j]);	 
	
	// return pointer of the reversed string 
	return rev; 
} 

// Driver code 
int main(void) 
{ 
	const char *s = "GeeksforGeeks"; 
	printf("%s", reverseConstString(s)); 
	return (0); 
} 

5. Reverse string using the constructor :

Passing reverse iterators to the constructor returns us a reversed string.

// A simple C++ program to reverse string using constructor 
#include <bits/stdc++.h> 
using namespace std; 
int main(){ 

	string str = "GeeksforGeeks"; 

	//Use of reverse iterators 
	string rev = string(str.rbegin(),str.rend()); 

	cout<<rev<<endl; 
	return 0; 
} 
  • 17
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值