Open In App

Reverse middle words of a string

Last Updated : 12 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str, print reverse all words except the first and last words.

Examples: 

Input  : Hi how are you geeks 
Output  : Hi woh era uoy geeks

Input : I am fine
Output : I ma fine
  1. Print the first word.
  2. For remaining middle words, print the reverse of every word after reaching end of it. This will print reverse of all words except the last word.
  3. Print the last word.

Implementation:

C++




// CPP program to print reverse of all words
// except the corner words.
#include <bits/stdc++.h>
using namespace std;
 
void printReverse(string str)
{
    // Print first word
    int i = 0;
    for (i = 0; i < str.length() && str[i] != ' '; i++)
        cout << str[i];
 
    // Print middle words
    string word = "";
    for (; i < str.length(); i++) {
 
        if (str[i] != ' ')
            word += str[i];
        else {
            reverse(word.begin(), word.end());
            cout << word << " ";
            word = "";
        }
    }
 
    // Print last word
    cout << word << " ";
}
 
int main()
{
    string str = "Hi how are you geeks";
    printReverse(str);
    return 0;
}


Java




// Java program to print reverse of all words
// except the corner words.
 
public class GFG{
 
static void printReverse(String str)
    {
        // Print first word
        int i = 0;
        for (i = 0; i < str.length() && str.charAt(i) != ' '; i++)
            System.out.print(str.charAt(i)) ;
     
        // Print middle words
        String word = "";
         
         
        for (; i < str.length(); i++) {
     
            if (str.charAt(i) != ' ')
                word += str.charAt(i);
                 
            else {
                    System.out.print(new StringBuilder(word).
                                reverse().toString() + " ");
                    word = "";
            }
        }
     
        // Print last word
        System.out.print(word + " ");
    }
     
    public static void main(String []args)
    {
        String str = "Hi how are you geeks";
        printReverse(str);
    }
 
// This code is contributed by Ryuga
}


Python3




# Python3 program to print reverse of all words
# except the corner words.
def printReverse(s):
 
    #Taking all the words in a list
    l = [s for s in s.split(' ')]
 
    #printing the first word as it is
    print(l[0], end = ' ')
 
     
    for i in range(1, len(l)-1):
 
        #printing middle words reversed
        print(l[i][::-1], end = ' ')
 
    #printing the last word as it is
    print(l[len(l)-1])
 
s = "Hi how are you geeks"
printReverse(s)


C#




// C# program to print reverse of all words
// except the corner words.
using System;
using System.Text;
 
class GFG
{
 
    static void printReverse(String str)
    {
        // Print first word
        int i = 0;
        for (i = 0; i < str.Length && str[i] != ' '; i++)
            Console.Write(str[i]) ;
     
        // Print middle words
        String word = "";
         
         
        for (; i < str.Length; i++)
        {
     
            if (str[i] != ' ')
                word += str[i];
                 
            else
            {
                word = reverse(word);
                    Console.Write(new StringBuilder(word).ToString() + " ");
                    word = "";
            }
        }
     
        // Print last word
        Console.Write(word + " ");
    }
    static String reverse(String input)
    {
        char[] temparray = input.ToCharArray();
        int left, right = 0;
        right = temparray.Length - 1;
 
        for (left = 0; left < right; left++, right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return String.Join("",temparray);
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String str = "Hi how are you geeks";
        printReverse(str);
    }
}
 
// This code contributed by Rajput-Ji


PHP




<?php
// PHP program to print reverse of all
// words except the corner words.
function printReverse($str)
{
    // Print first word
    $i = 0;
    for ($i = 0; $i < strlen($str) &&
                 $str[$i] != ' '; $i++)
        echo $str[$i];
 
    // Print middle words
    $word = "";
    for (; $i < strlen($str); $i++)
    {
 
        if ($str[$i] != ' ')
            $word = $word.$str[$i];
        else
        {
            $word = strrev($word);
            echo $word . " ";
            $word = "";
        }
    }
 
    // Print last word
    echo $word . " ";
}
 
// Driver Code
$str = "Hi how are you geeks";
printReverse($str);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// JavaScript program to print reverse of
// all words except the corner words.
function printReverse(str)
{
     
    // Print first word
    var i = 0;
    for(i = 0;
        i < str.length && str[i] != " ";
        i++)
        document.write(str[i]);
     
    // Print middle words
    var word = "";
    for(; i < str.length; i++)
    {
        if (str[i] != " ")
            word += str[i];
        else
        {
            var temp = word.split("").reverse().join("");
            document.write(temp + " ");
            word = "";
        }
    }
     
    // Print last word
    document.write(word + " ");
}
 
// Driver code
var str = "Hi how are you geeks";
printReverse(str);
 
// This code is contributed by rdtank
 
</script>


Output

Hi woh era uoy geeks 

Complexity Analysis:

  • Time Complexity: O(n) 
  • Auxiliary Space: O(L) where L is the length of the longest word in the string.


Similar Reads

Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
17 min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Sorting array with reverse around middle
Consider the given array arr[], we need to find if we can sort array with the given operation. The operation is We have to select a subarray from the given array such that the middle element(or elements (in case of even number of elements)) of subarray is also the middle element(or elements (in case of even number of elements)) of the given array.
6 min read
Reverse Middle X Characters
Given a string str and an integer X. The task is to reverse the middle X characters of the given string and then print the modified string. Note that len(str) - X is always even.Examples: Input: str = "geeksforgeeks", X = 3 Output: geeksrofgeeks Middle three character are "geeksforgeeks" Hence the resultant string is "geeksrofgeeks"Input: str = "ac
9 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Reverse String according to the number of words
Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajput Sunil Pundir Output: ridnuP tupjaR vadaY Ashish
6 min read
Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
Program to reverse words in a given string in C++
Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. Examples: Input: str = "the sky is blue" Output: blue is sky theInput: str = "I love programming" Output: programming love I Method 1: Using STL functions Reverse the given string str using STL function reverse().Iterate the reversed string an
6 min read
Reverse words in a given string | Set 2
Given string str, the task is to reverse the string by considering each word of the string, str as a single unit. Examples: Input: str = “geeks quiz practice code”Output: code practice quiz geeks Explanation: The words in the given string are [“geeks”, “quiz”, “practice”, “code”]. Therefore, after reversing the order of the words, the required outp
9 min read
Reverse words in a given string
Given a string, the task is to reverse the order of the words in the given string. Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "i love programming very much" Output: s = "much very programming love i" Recommended PracticeReverse words in a given stringTry It!Approach: Initially, reverse the indi
31 min read
Article Tags :
Practice Tags :