Here, we have a basic program example to reverse a string using different languages. This program is created in c language, c++, Java, and Python.
Program to reverse a string in C language
#include <stdio.h>
#include <string.h>
int main()
{
char str[30];
printf (" \n Enter a string to be reversed: ");
scanf ("%s", str);
printf (" \n After the reverse of a string: %s ", strrev(str));
return 0;
}
Program to reverse a string in C++ language
#include <iostream>
using namespace std;
void revstr(string str)
{
int i, len;
char temp;
len = str.length();
for (i = 0; i < len / 2; i++) {
temp = str.at(i);
str.at(i) =str.at(len - i - 1);
str[len - i - 1] = temp;
}
cout << "After reversing the string: " << str << endl;
}
int main()
{
string str;
cout<<"Enter the string";
cin>>str;
cout << "Before reversing the string: " << str << endl;
revstr(str);
return 0;
}
Program to reverse a string in Python language
str=input("Enter the string: ")
print("The original string is: ", str)
reverse_String = ""
count = len(str)
while count > 0:
reverse_String += str[count - 1]
count = count - 1
print("The reversed string is : ", reverse_String)
Program to reverse a string in Java language
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String :");
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}