Program to reverse a sentence
Last Updated :
19 Jan, 2024
Write a program to reverse a sentence.
Examples:
Input: “Practice with GFG”
Output: “GFG htiw ecitcarP”
Input: “Programming is fun”
Output: “nuf si gnimmargorP”
Approach: To solve the problem, follow the below idea:
It can be observed that we can reverse a sentence by traversing over the original sentence in reverse order and then pushing the characters from the back to a new string. Finally, return the final string.
Step-by-step algorithm:
- Create a variable to store the reversed sentence.
- Traverse the original sentence from the last character to the first.
- Append each character to the reversed sentence.
Below is the implementation of the algorithm:
C++
#include <iostream>
using namespace std;
string reverseSentence(string sentence)
{
string reversedString = "" ;
for ( int i = sentence.length() - 1; i >= 0; i--) {
reversedString.push_back(sentence[i]);
}
return reversedString;
}
int main()
{
string sentence = "Practice with GFG" ;
cout << reverseSentence(sentence) << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
char * reverseSentence( const char * sentence) {
int length = strlen (sentence);
char * reversedString = ( char *) malloc ((length + 1) * sizeof ( char ));
for ( int i = length - 1, j = 0; i >= 0; i--, j++) {
reversedString[j] = sentence[i];
}
reversedString[length] = '\0' ;
return reversedString;
}
int main() {
const char * sentence = "Practice with GFG" ;
char * reversed = reverseSentence(sentence);
printf ( "%s\n" , reversed);
free (reversed);
return 0;
}
|
Java
public class ReverseSentence {
public static String reverseSentence(String sentence)
{
StringBuilder reversedString = new StringBuilder();
for ( int i = sentence.length() - 1 ; i >= 0 ; i--) {
reversedString.append(sentence.charAt(i));
}
return reversedString.toString();
}
public static void main(String[] args)
{
String sentence = "Practice with GFG" ;
System.out.println(reverseSentence(sentence));
}
}
|
Python3
def reverse_sentence(sentence):
reversed_string = ""
for i in range ( len (sentence) - 1 , - 1 , - 1 ):
reversed_string + = sentence[i]
return reversed_string
if __name__ = = "__main__" :
sentence = "Practice with GFG"
print (reverse_sentence(sentence))
|
C#
using System;
class Program {
static string ReverseSentence( string sentence)
{
char [] charArray = sentence.ToCharArray();
Array.Reverse(charArray);
return new string (charArray);
}
static void Main()
{
string sentence = "Practice with GFG" ;
Console.WriteLine(ReverseSentence(sentence));
}
}
|
Javascript
function reverseSentence(sentence) {
return sentence.split( '' ).reverse().join( '' );
}
const sentence = "Practice with GFG" ;
console.log(reverseSentence(sentence));
|
Time Complexity: O(N), where N is the length of the sentence.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...