Program to Reverse a String

Description

Reverse of a string means to swap the first character with last character,
second character with second last character and so on.

C/C++

/* C program to reverse a string */
//Save it as ReverseString.c

#include<stdio.h>
int main(){

    char str[100], revStr[100];
    int i, j=0;

    printf("Enter a string : ");
    gets(str);

    for(i=strlen(str)-1;i>=0;i--){
        revStr[j++] = str[i];
    }
    revStr[j] = '\0';

    printf("Reverse of %s is %s",str,revStr);

    
    /* The library function strrev(str) reverses all characters
       in the string except null character*/
    // It is defined in string.h header file
    

    printf("\nReverse of %s is %s",str,strrev(str));

    return 0;
}
Input:
Enter a string : 
Virat Kohli

Output:
The reverse of Virat Kohli is ilhoK tariV

Java

/* Java program to reverse a string */
//Save it as ReverseString.java

import java.io.*;
import java.util.Scanner;
public class ReverseString {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a string : ");
        String str = scanner.nextLine();
        
        //Convert string to character array so that every character can be accessed
        
        char ch[] = str.toCharArray();
        
        
        //Declaring a null string
        
        String rev = "";
        
        
        //Traversing string from end
        
        for(int i=ch.length-1;i>=0;i--) {
            
            //Appending the character from end to string rev
            
            rev+= ch[i];
        }
        
        System.out.println("The reverse of "+str+" is "+rev);
    }
}
Input:
Enter a string : 
Virat Kohli

Output:
The reverse of Virat Kohli is ilhoK tariV

Related Programs

1) Program to Compare Two Strings
2) Find Substring of a Given String
3) Program to Insert a String into Another String
4) Program to check String is Palindrome
5) Program to copy string
6) Program to remove vowels from a String
7) Program to Multiply Numbers Present in a String
8) Program to remove given number from a string
9) Count Number of Words in a String
10) Program to Sort set of strings in alphabetical order
Share Me

Leave a Reply