
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
Reverse a String in C/C++
Here is an example to reverse a string in C language,
Example
#include<stdio.h> #include<string.h> int main() { char s[50], t; int i = 0, j = 0; printf("\nEnter the string to reverse :"); gets(s); j = strlen(s) - 1; while (i < j) { t = s[i]; s[i] = s[j]; s[j] = t; i++; j--; } printf("\nReverse string is : %s", s); return (0); }
Output
Here is the output
Enter the string to reverse: Here is the input string. Reverse string is : .gnirts tupni eht si ereH
In the above program, the actual code to reverse a string is present in main(). A char type array is declared char[50] which will store the input string given by user.
Then, we are calculating the length of string using library function strlen().
j = strlen(s) - 1;
Then, we are swapping the characters at position i and j. The variable i is incremented and j is decremented.
while (i < j) { t = s[i]; s[i] = s[j]; s[j] = t; i++; j--; }
Advertisements