Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Different methods to reverse a string in C/C++
In this tutorial, we will be discussing a program to understand different methods to reverse a string in C/C++.
Example
User-defined reverse() function −
#include <bits/stdc++.h>
using namespace std;
//function to reverse given string
void reverse_str(string& str){
int n = str.length();
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int main(){
string str = "tutorialspoint";
reverse_str(str);
cout << str;
return 0;
}
Using in-built reverse() function −
#include <bits/stdc++.h>
using namespace std;
int main(){
string str = "tutorialspoint";
reverse(str.begin(), str.end());
cout << str;
return 0;
}
Printing reverse of a given string−
#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
for (int i=str.length()-1; i>=0; i--)
cout << str[i];
}
int main(void){
string s = "tutorialspoint";
reverse(s);
return (0);
}
Output
tniopslairotut
Advertisements