Table of Contents
The program to reverse a given string takes the input string and output reverse of the string. Each of the characters from the input string is extracted one at a time to achieve this task.
Problem Definition
The program takes an input string at run-time using the built-in function fgets (str) where str is a character array. In this array of characters, the beginning characters are exchanged with the ending characters of the string with the help of a temp variable.
For example
If the string is “ELEPHANT”. The letter is ‘E’ and ‘T’ are exchanged until all characters are reversed. The final output is TNAHPELE.
Program Codes – Reverse a String
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], temp;
int i, j;
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
/* Remove newline character if present */
str[strcspn(str, "\n")] = '\0';
i = 0;
j = strlen(str) - 1;
while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("Reverse string is: %s\n", str);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Enter the string: ";
getline(cin, str);
int i = 0, j = str.length() - 1;
while (i < j)
{
swap(str[i], str[j]);
i++;
j--;
}
cout << "Reverse string is: " << str << endl;
return 0;
}import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = sc.nextLine();
char[] ch = str.toCharArray();
int i = 0, j = ch.length - 1;
while (i < j) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i++;
j--;
}
System.out.println("Reverse string is: " + new String(ch));
sc.close();
}
}s = input("Enter the string: ")
rev = s[::-1]
print("Reverse string is:", rev)Output
The output of the above program is given below. When the program ask for a string input, the user enters – MATHEMATICS. The program reverses the string and give following output.
Enter the String: MATHEMATICS
Reverse String is SCITAMEHTAM