Reverse the word order

Reverse the entire string, then reverse the letters of each individual word.

After the first pass the string will be

s1 = "Z Y X si eman yM"

and after the second pass it will be

s1 = "Z Y X is name My"

11

reverse the string and then, in a second pass, reverse each word…

in c#, completely in-place without additional arrays:

static char[] ReverseAllWords(char[] in_text)
{
    int lindex = 0;
    int rindex = in_text.Length - 1;
    if (rindex > 1)
    {
        //reverse complete phrase
        in_text = ReverseString(in_text, 0, rindex);

        //reverse each word in resultant reversed phrase
        for (rindex = 0; rindex <= in_text.Length; rindex++)
        {
            if (rindex == in_text.Length || in_text[rindex] == ' ')
            {
                in_text = ReverseString(in_text, lindex, rindex - 1);
                lindex = rindex + 1;
            }
        }
    }
    return in_text;
}

static char[] ReverseString(char[] intext, int lindex, int rindex)
{
    char tempc;
    while (lindex < rindex)
    {
        tempc = intext[lindex];
        intext[lindex++] = intext[rindex];
        intext[rindex--] = tempc;
    }
    return intext;
}

3

Not exactly in place, but anyway: Python:

>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'

2

In Smalltalk:

'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]

I know noone cares about Smalltalk, but it’s so beautiful to me.

0

You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered «in place», but it’s not completely «extra data structure free».

Below is code implementing what Bill the Lizard describes:

string words = "this is a test";

// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
  char temp = words[i];
  words[i] = words[strlen(words) - i];
  words[strlen(words) - i] = temp;
}

// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
  int wordstart = -1;
  int wordend = -1;
  if(words[i] != ' ') {
    wordstart = i;
    for(int j = wordstart; j < strlen(words); ++j) {
      if(words[j] == ' ') {
        wordend = j - 1;
        break;
      }
    }
    if(wordend == -1)
      wordend = strlen(words);
    for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
      char temp = words[j];
      words[j] = words[wordend - (j - wordstart)];
      words[wordend - (j - wordstart)] = temp;
    }
    i = wordend;
  }
}

3

What language?
If PHP, you can explode on space, then pass the result to array_reverse.

If its not PHP, you’ll have to do something slightly more complex like:

words = aString.split(" ");
for (i = 0; i < words.length; i++) {
    words[i] = words[words.length-i];
}

2

public static String ReverseString(String str)
{
    int word_length = 0;
    String result = "";
    for (int i=0; i<str.Length; i++)
    {
        if (str[i] == ' ')
        {
            result = " " + result;
            word_length = 0;
        } else 
        {
            result = result.Insert(word_length, str[i].ToString());
            word_length++;
        }
    }
    return result;
}

This is C# code.

0

In Python...

ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)

Anyway cookamunga provided good inline solution using python!

1

This is assuming all words are separated by spaces:

#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "What are you looking at";
    int i, n = strlen(string);

    int tail = n-1;
    for(i=n-1;i>=0;i--)
    {
        if(string[i] == ' ' || i == 0)
        {
            int cursor = (i==0? i: i+1);
            while(cursor <= tail)
                printf("%c", string[cursor++]);
            printf(" ");
            tail = i-1;
        }
    }
    return 0;
}

class Program
{
    static void Main(string[] args)
    {
        string s1 =" My Name varma:;
        string[] arr = s1.Split(' ');
        Array.Reverse(arr);
        string str = string.Join(" ", arr);
        Console.WriteLine(str);
        Console.ReadLine();

    }
}

This is not perfect but it works for me right now. I don’t know if it has O(n) running time btw (still studying it ^^) but it uses one additional array to fulfill the task.

It is probably not the best answer to your problem because i use a dest string to save the reversed version instead of replacing each words in the source string. The problem is that i use a local stack variable named buf to copy all the words in and i can not copy but into the source string as this would lead to a crash if the source string is const char * type.

But it was my first attempt to write s.th. like this :) Ok enough blablub. here is code:

#include <iostream>
using namespace std;

void reverse(char *des, char * const s);
int main (int argc, const char * argv[])
{    
    char* s = (char*)"reservered. rights All Saints. The 2011 (c) Copyright 11/10/11 on Pfundstein Markus by Created";
    char *x = (char*)"Dogfish! White-spotted Shark, Bullhead";

    printf("Before: |%s|n", x);
    printf("Before: |%s|n", s);

    char *d = (char*)malloc((strlen(s)+1)*sizeof(char));  
    char *i = (char*)malloc((strlen(x)+1)*sizeof(char));

    reverse(d,s);
    reverse(i,x);

    printf("After: |%s|n", i);
    printf("After: |%s|n", d);

    free (i);
    free (d);

    return 0;
}

void reverse(char *dest, char *const s) {
    // create a temporary pointer
    if (strlen(s)==0) return;
    unsigned long offset = strlen(s)+1;

    char *buf = (char*)malloc((offset)*sizeof(char));
    memset(buf, 0, offset);

    char *p;
    // iterate from end to begin and count how much words we have
    for (unsigned long i = offset; i != 0; i--) {
        p = s+i;
        // if we discover a whitespace we know that we have a whole word
        if (*p == ' ' || *p == '') {
            // we increment the counter
            if (*p != '') {
                // we write the word into the buffer
                ++p;
                int d = (int)(strlen(p)-strlen(buf));
                strncat(buf, p, d);
                strcat(buf, " ");
            }
        }
    }

    // copy the last word
    p -= 1;
    int d = (int)(strlen(p)-strlen(buf));
    strncat(buf, p, d);
    strcat(buf, "");

    // copy stuff to destination string
    for (int i = 0; i < offset; ++i) {
        *(dest+i)=*(buf+i);
    }

    free(buf);
}

We can insert the string in a stack and when we extract the words, they will be in reverse order.

void ReverseWords(char Arr[])
{
    std::stack<std::string> s;
    char *str;
    int length = strlen(Arr);
    str = new char[length+1];
    std::string ReversedArr;
    str = strtok(Arr," ");
    while(str!= NULL)
    {
        s.push(str);
        str = strtok(NULL," ");
    }
    while(!s.empty())
    {
        ReversedArr = s.top();
        cout << " " << ReversedArr;
        s.pop();
    }
}

This quick program works..not checks the corner cases though.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    char word[50];
    struct node *next;
};
struct stack
{
    struct node *top;
};
void print (struct stack *stk);
void func (struct stack **stk, char *str);
main()
{
    struct stack *stk = NULL;
    char string[500] = "the sun is yellow and the sky is blue";
    printf("n%sn", string);
    func (&stk, string);
    print (stk);
}
void func (struct stack **stk, char *str)
{
    char *p1 = str;
    struct node *new = NULL, *list = NULL;
    int i, j;
    if (*stk == NULL)
    {
        *stk = (struct stack*)malloc(sizeof(struct stack));
        if (*stk == NULL)
            printf("n####### stack is not allocated #####n");
        (*stk)->top = NULL;
    }
    i = 0;
    while (*(p1+i) != '')
    {
        if (*(p1+i) != ' ')
        {
            new = (struct node*)malloc(sizeof(struct node));
            if (new == NULL)
                printf("n####### new is not allocated #####n");
            j = 0;
            while (*(p1+i) != ' ' && *(p1+i) != '')
            {
                new->word[j] = *(p1 + i);
                i++;
                j++;
            }
            new->word[j++] = ' ';
            new->word[j] = '';
            new->next = (*stk)->top;
            (*stk)->top = new;
        }
        i++;
   }
}
void print (struct stack *stk)
{
    struct node *tmp = stk->top;
    int i;
    while (tmp != NULL)
    {
        i = 0;
        while (tmp->word[i] != '')
        {
            printf ("%c" , tmp->word[i]);
            i++;
        }
        tmp = tmp->next;
    }
    printf("n");
}

2

Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of str=" Hello world"… The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting in f(str) == "world Hello ".

The OP said «I want to reverse the order of the words» and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I’ll provide a [hopefully] more correct one in C++:

#include <string>
#include <algorithm>

void strReverseWords_inPlace(std::string &str)
{
  const char delim = ' ';
  std::string::iterator w_begin, w_end;
  if (str.size() == 0)
    return;

  w_begin = str.begin();
  w_end   = str.begin();

  while (w_begin != str.end()) {
    if (w_end == str.end() || *w_end == delim) {
      if (w_begin != w_end)
        std::reverse(w_begin, w_end);
      if (w_end == str.end())
        break;
      else
        w_begin = ++w_end;
    } else {
      ++w_end;
    }
  }

  // instead of reversing str.begin() to str.end(), use two iterators that
  // ...represent the *logical* begin and end, ignoring leading/traling delims
  std::string::iterator str_begin = str.begin(), str_end = str.end();
  while (str_begin != str_end && *str_begin == delim)
    ++str_begin;
  --str_end;
  while (str_end != str_begin && *str_end == delim)
    --str_end;
  ++str_end;
  std::reverse(str_begin, str_end);
}

My version of using stack:

public class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        String ns= s.trim();
        Stack<Character> reverse = new Stack<Character>();
        boolean hadspace=false;

        //first pass
        for (int i=0; i< ns.length();i++){
            char c = ns.charAt(i);
            if (c==' '){
                if (!hadspace){
                    reverse.push(c);
                    hadspace=true;
                }
            }else{
                hadspace=false;
                reverse.push(c);
            }
        }
        Stack<Character> t = new Stack<Character>();
        while (!reverse.empty()){
            char temp =reverse.pop();
            if(temp==' '){
                //get the stack content out append to StringBuilder
                while (!t.empty()){
                    char c =t.pop();
                    sb.append(c);
                }
                sb.append(' ');
            }else{
                //push to stack
                t.push(temp);
            }
        }
        while (!t.empty()){
            char c =t.pop();
            sb.append(c);
        }
        return sb.toString();
    }
}

Store Each word as a string in array then print from end

public void rev2() {
    String str = "my name is ABCD";
    String A[] = str.split(" ");

    for (int i = A.length - 1; i >= 0; i--) {
        if (i != 0) {
            System.out.print(A[i] + " ");
        } else {
            System.out.print(A[i]);
        }
    }

}

In Python, if you can’t use [::-1] or reversed(), here is the simple way:

def reverse(text):

  r_text = text.split(" ")
  res = []
  for word in range(len(r_text) - 1, -1, -1): 
    res.append(r_text[word])

  return " ".join(res)

print (reverse("Hello World"))

>> World Hello
[Finished in 0.1s]

Printing words in reverse order of a given statement using C#:

    void ReverseWords(string str)
    {
        int j = 0;
        for (int i = (str.Length - 1); i >= 0; i--)
        {
            if (str[i] == ' ' || i == 0)
            {
                j = i == 0 ? i : i + 1;

                while (j < str.Length && str[j] != ' ')
                    Console.Write(str[j++]);
                Console.Write(' ');
            }
        }
    }

Here is the Java Implementation:

public static String reverseAllWords(String given_string)
{
    if(given_string == null || given_string.isBlank())
        return given_string;

    char[] str = given_string.toCharArray();
    int start = 0;

    // Reverse the entire string
    reverseString(str, start, given_string.length() - 1);

    // Reverse the letters of each individual word
    for(int end = 0; end <= given_string.length(); end++)
    {
        if(end == given_string.length() || str[end] == ' ')
        {
            reverseString(str, start, end-1);
            start = end + 1;
        }
    }
    return new String(str);
}

// In-place reverse string method
public static void reverseString(char[] str, int start, int end)
{
    while(start < end)
    {
        char temp = str[start];
        str[start++] = str[end];
        str[end--] = temp;
    }
}

Actually, the first answer:

words = aString.split(" ");
for (i = 0; i < words.length; i++) {
    words[i] = words[words.length-i];
}

does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:

words = aString.split(" "); // make up a list
i = 0; j = words.length - 1; // find the first and last elements
while (i < j) {
    temp = words[i]; words[i] = words[j]; words[j] = temp; //i.e. swap the elements
    i++; 
    j--;
}

Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.

2

How about …

var words = "My name is X Y Z";
var wr = String.Join( " ", words.Split(' ').Reverse().ToArray() );

I guess that’s not in-line tho.

2

In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).

#include<stdio.h>
#include<stdlib.h>
main(){
  char* a = malloc(1000);
  fscanf(stdin, "%[^n]", a);
  int x = 0, y;
  while(a[x]!='')
  {
    if (a[x]==' ' || a[x]=='n')
    {
      x++;
    }
    else
    {
      y=x;
      while(a[y]!='' && a[y]!=' ' && a[y]!='n')
      { 
        y++;
      }
      int z=y;
      while(x<y)
      {
        y--;
        char c=a[x];a[x]=a[y];a[y]=c; 
        x++;
      }
      x=z;
    }
  }

  fprintf(stdout,a);
  return 0;
}

It can be done more simple using sscanf:

void revertWords(char *s);
void revertString(char *s, int start, int n);
void revertWordsInString(char *s);

void revertString(char *s, int start, int end)
{
     while(start<end)
     {
         char temp = s[start];
         s[start] = s[end];
         s[end]=temp;
         start++;
         end --;
     }
}


void revertWords(char *s)
{
  int start = 0;

  char *temp = (char *)malloc(strlen(s) + 1);
  int numCharacters = 0;
  while(sscanf(&s[start], "%s", temp) !=EOF)
  {
      numCharacters = strlen(temp);

      revertString(s, start, start+numCharacters -1);
      start = start+numCharacters + 1;
      if(s[start-1] == 0)
      return;

  }
  free (temp);

}

void revertWordsInString(char *s)
{
   revertString(s,0, strlen(s)-1);
   revertWords(s);
}

int main()
{
   char *s= new char [strlen("abc deff gh1 jkl")+1];
   strcpy(s,"abc deff gh1 jkl");
   revertWordsInString(s);
   printf("%s",s);
   return 0;
}

import java.util.Scanner;

public class revString {
   static char[] str;

   public static void main(String[] args) {
    //Initialize string
    //str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
    //'r', 'l', 'd' };
    getInput();

    // reverse entire string
    reverse(0, str.length - 1);

    // reverse the words (delimeted by space) back to normal
    int i = 0, j = 0;
    while (j < str.length) {

        if (str[j] == ' ' || j == str.length - 1) {

            int m = i;
            int n;

            //dont include space in the swap. 
            //(special case is end of line)
            if (j == str.length - 1)
                n = j;
            else
                n = j -1;


            //reuse reverse
            reverse(m, n);

            i = j + 1;

        }
        j++;
    }

    displayArray();
}

private static void reverse(int i, int j) {

    while (i < j) {

        char temp;
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;

        i++;
        j--;
    }
}
private static void getInput() {
    System.out.print("Enter string to reverse: ");
    Scanner scan = new Scanner(System.in);
    str = scan.nextLine().trim().toCharArray(); 
}

private static void displayArray() {
    //Print the array
    for (int i = 0; i < str.length; i++) {
        System.out.print(str[i]);
    }
}

}

In Java using an additional String (with StringBuilder):

public static final String reverseWordsWithAdditionalStorage(String string) {
    StringBuilder builder = new StringBuilder();

    char c = 0;
    int index = 0;
    int last = string.length();
    int length = string.length()-1;
    StringBuilder temp = new StringBuilder();
    for (int i=length; i>=0; i--) {
        c = string.charAt(i);
        if (c == SPACE || i==0) {
            index = (i==0)?0:i+1;
            temp.append(string.substring(index, last));
            if (index!=0) temp.append(c);
            builder.append(temp);
            temp.delete(0, temp.length());
            last = i;
        }
    }

    return builder.toString();
}

In Java in-place:

public static final String reverseWordsInPlace(String string) {
    char[] chars = string.toCharArray();

    int lengthI = 0;
    int lastI = 0;
    int lengthJ = 0;
    int lastJ = chars.length-1;

    int i = 0;
    char iChar = 0;
    char jChar = 0;
    while (i<chars.length && i<=lastJ) {
        iChar = chars[i];
        if (iChar == SPACE) {
            lengthI = i-lastI;
            for (int j=lastJ; j>=i; j--) {
                jChar = chars[j];
                if (jChar == SPACE) {
                    lengthJ = lastJ-j;
                    swapWords(lastI, i-1, j+1, lastJ, chars);
                    lastJ = lastJ-lengthI-1;
                    break;
                }
            }
            lastI = lastI+lengthJ+1;
            i = lastI;
        } else {
            i++;
        }
    }

    return String.valueOf(chars);
}

private static final void swapWords(int startA, int endA, int startB, int endB, char[] array) {
    int lengthA = endA-startA+1;
    int lengthB = endB-startB+1;

    int length = lengthA;
    if (lengthA>lengthB) length = lengthB;

    int indexA = 0;
    int indexB = 0;
    char c = 0;
    for (int i=0; i<length; i++) {
        indexA = startA+i;
        indexB = startB+i;

        c = array[indexB];
        array[indexB] = array[indexA];
        array[indexA] = c;
    }

    if (lengthB>lengthA) {
        length = lengthB-lengthA;
        int end = 0;
        for (int i=0; i<length; i++) {
            end = endB-((length-1)-i);
            c = array[end];
            shiftRight(endA+i,end,array);
            array[endA+1+i] = c;
        }
    } else if (lengthA>lengthB) {
        length = lengthA-lengthB;
        for (int i=0; i<length; i++) {
            c = array[endA];
            shiftLeft(endA,endB,array);
            array[endB+i] = c;
        }
    }
}

private static final void shiftRight(int start, int end, char[] array) {
    for (int i=end; i>start; i--) {
        array[i] = array[i-1];
    }
}

private static final void shiftLeft(int start, int end, char[] array) {
    for (int i=start; i<end; i++) {
        array[i] = array[i+1];
    }
}

Here is a C implementation that is doing the word reversing inlace, and it has O(n) complexity.

char* reverse(char *str, char wordend=0)
{
    char c;
    size_t len = 0;
    if (wordend==0) {
        len = strlen(str);
    }
    else {
        for(size_t i=0;str[i]!=wordend && str[i]!=0;i++)
            len = i+1;
    }
            for(size_t i=0;i<len/2;i++) {
                c = str[i];
                str[i] = str[len-i-1];
                str[len-i-1] = c;
            }
    return str;
}

char* inplace_reverse_words(char *w)
{
    reverse(w); // reverse all letters first
    bool is_word_start = (w[0]!=0x20);

    for(size_t i=0;i<strlen(w);i++){
        if(w[i]!=0x20 && is_word_start) {
            reverse(&w[i], 0x20); // reverse one word only
            is_word_start = false;
        }
        if (!is_word_start && w[i]==0x20) // found new word
            is_word_start = true;
    }
    return w;
}

c# solution to reverse words in a sentence

using System;
class helloworld {
    public void ReverseString(String[] words) {
        int end = words.Length-1;
        for (int start = 0; start < end; start++) {
            String tempc;
            if (start < end ) {
                tempc = words[start];
                words[start] = words[end];
                words[end--] = tempc;
            }
        }
        foreach (String s1 in words) {
            Console.Write("{0} ",s1);
        }
    }
}
class reverse {
    static void Main() {
        string s= "beauty lies in the heart of the peaople";
        String[] sent_char=s.Split(' ');
        helloworld h1 = new helloworld();
        h1.ReverseString(sent_char);
    }
}

output:
peaople the of heart the in lies beauty Press any key to continue . . .

0

Better version
Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html

public string reverseTheWords(string description)
{
    if(!(string.IsNullOrEmpty(description)) && (description.IndexOf(" ") > 1))
    {
        string[] words= description.Split(' ');
        Array.Reverse(words);
        foreach (string word in words)
        {
            string phrase = string.Join(" ", words);
            Console.WriteLine(phrase);
        }
        return phrase;
    }
    return description;
}

public class manip{

public static char[] rev(char[] a,int left,int right) {
    char temp;
    for (int i=0;i<(right - left)/2;i++)    {
        temp = a[i + left];
        a[i + left] = a[right -i -1];
        a[right -i -1] = temp;
    }

    return a;
}
public static void main(String[] args) throws IOException {

    String s= "i think this works";
    char[] str = s.toCharArray();       
    int i=0;
    rev(str,i,s.length());
    int j=0;
    while(j < str.length) {
        if (str[j] != ' ' && j != str.length -1) {
            j++;
        } else
        {
            if (j == (str.length -1))   {
                j++;
            }
            rev(str,i,j);
            i=j+1;
            j=i;
        }
    }
    System.out.println(str);
}

I know there are several correct answers. Here is the one in C that I came up with.
This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.

#include<stdio.h>

char * strRev(char *str, char tok)
{
   int len = 0, i;
   char *temp = str;
   char swap;

   while(*temp != tok && *temp != '') {
      len++; temp++;
   }   
   len--;

   for(i = 0; i < len/2; i++) {
      swap = str[i];
      str[i] = str[len - i]; 
      str[len - i] = swap;
   }   

   // Return pointer to the next token.
   return str + len + 1;
}

int main(void)
{
   char a[] = "Reverse this string.";
   char *temp = a;

   if (a == NULL)
      return -1; 

   // Reverse whole string character by character.
   strRev(a, '');

   // Reverse every word in the string again.
   while(1) {
      temp = strRev(temp, ' ');
      if (*temp == '')
         break;

      temp++;
   }   
   printf("Reversed string: %sn", a); 
   return 0;
}

1

#include <iostream>

#include <algorithm>

using namespace std;

int main() {

string str = «you shall not pass»;

cout << «Original string: » << str << endl;

// Use the built-in reverse to get char-by-char reversal.

reverse(str.begin(), str.end());

string buffer = «»;

string ans = «»;

// This for loop then reverses each individual

// word in the string.

for (int i=0; i < str.length(); i++)

{

if (str[i] != ‘ ‘)

{

buffer += str[i];

}

else

{

reverse(buffer.begin(), buffer.end());

ans += buffer + » «;

buffer = «»;

}

}

// Reversing the last word in the string outside the loop:

reverse(buffer.begin(), buffer.end());

ans += buffer;

cout << «Reversed string: » << ans << endl;

}

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” 

reverse-words

Approach:

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Follow the below steps to solve the problem:

  • Run a for loop to traverse the string and create a temporary string to store the words
  • If the current character is a space then add the current string to the answer and empty the string
  • Else push the character into the string
  • Print the answer array in reverse order 

Below is the implementation of the above approach: 

C++

#include <bits/stdc++.h>

using namespace std;

void reverseWords(string s)

{

    vector<string> tmp;

    string str = "";

    for (int i = 0; i < s.length(); i++) {

        if (s[i] == ' ') {

            tmp.push_back(str);

            str = "";

        }

        else

            str += s[i];

    }

    tmp.push_back(str);

    int i;

    for (i = tmp.size() - 1; i > 0; i--)

        cout << tmp[i] << " ";

    cout << tmp[0] << endl;

}

int main()

{

    string s = "i like this program very much";

    reverseWords(s);

    return 0;

}

C

#include <stdio.h>

void reverse(char* begin, char* end)

{

    char temp;

    while (begin < end) {

        temp = *begin;

        *begin++ = *end;

        *end-- = temp;

    }

}

void reverseWords(char* s)

{

    char* word_begin = s;

    char* temp = s;

    while (*temp) {

        temp++;

        if (*temp == '') {

            reverse(word_begin, temp - 1);

        }

        else if (*temp == ' ') {

            reverse(word_begin, temp - 1);

            word_begin = temp + 1;

        }

    }

    reverse(s, temp - 1);

}

int main()

{

    char s[] = "i like this program very much";

    char* temp = s;

    reverseWords(s);

    printf("%s", s);

    return 0;

}

Java

import java.util.*;

class GFG {

    static void reverse(char str[], int start, int end)

    {

        char temp;

        while (start <= end) {

            temp = str[start];

            str[start] = str[end];

            str[end] = temp;

            start++;

            end--;

        }

    }

    static char[] reverseWords(char[] s)

    {

        int start = 0;

        for (int end = 0; end < s.length; end++) {

            if (s[end] == ' ') {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.length - 1);

        reverse(s, 0, s.length - 1);

        return s;

    }

    public static void main(String[] args)

    {

        String s = "i like this program very much ";

        char[] p = reverseWords(s.toCharArray());

        System.out.print(p);

    }

}

Python3

def reverse_word(s, start, end):

    while start < end:

        s[start], s[end] = s[end], s[start]

        start = start + 1

        end -= 1

s = "i like this program very much"

s = list(s)

start = 0

while True:

    try:

        end = s.index(' ', start)

        reverse_word(s, start, end - 1)

        start = end + 1

    except ValueError:

        reverse_word(s, start, len(s) - 1)

        break

s.reverse()

s = "".join(s)

print(s)

C#

using System;

class GFG {

    static void reverse(char[] str, int start, int end)

    {

        char temp;

        while (start <= end) {

            temp = str[start];

            str[start] = str[end];

            str[end] = temp;

            start++;

            end--;

        }

    }

    static char[] reverseWords(char[] s)

    {

        int start = 0;

        for (int end = 0; end < s.Length; end++) {

            if (s[end] == ' ') {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.Length - 1);

        reverse(s, 0, s.Length - 1);

        return s;

    }

    public static void Main(String[] args)

    {

        String s = "i like this program very much ";

        char[] p = reverseWords(s.ToCharArray());

        Console.Write(p);

    }

}

Javascript

<script>

    function reverse(str,start,end)

    {

        let temp;

        while (start <= end)

        {

            temp = str[start];

            str[start]=str[end];

            str[end]=temp;

            start++;

            end--;

        }

    }

    function reverseWords(s)

    {

        s=s.split("");

        let start = 0;

        for (let end = 0; end < s.length; end++)

        {

            if (s[end] == ' ')

            {

                reverse(s, start, end);

                start = end + 1;

            }

        }

        reverse(s, start, s.length - 1);

        reverse(s, 0, s.length - 1);

        return s.join("");

    }

    var s = "i like this program very much ";

    document.write(reverseWords(s));

</script>

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(N)

Note: The above code doesn’t handle the cases when the string starts with space. 

Below is the implementation of the approach that handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. 

C++

#include <bits/stdc++.h>

using namespace std;

void reverse(string& s, int begin, int end)

{

    while (begin < end) {

        swap(s[begin++], s[end--]);

    }

}

void reverseWords(string& s)

{

    int word_begin = -1;

    int i = 0;

    while (i < s.size()) {

        if ((word_begin == -1) && (s[i] != ' ')) {

            word_begin = i;

        }

        if (word_begin != -1

            && ((s[i + 1] == ' ') || (i + 1 == s.size()))) {

            reverse(s, word_begin, i);

            word_begin = -1;

        }

        i++;

    }

    reverse(s, 0, s.size() - 1);

}

int main()

{

    string s = "i like this program very much";

    reverseWords(s);

    cout << s << endl;

    ;

    return 0;

}

C

#include <stdio.h>

void reverse(char* begin, char* end)

{

    char temp;

    while (begin < end) {

        temp = *begin;

        *begin++ = *end;

        *end-- = temp;

    }

}

void reverseWords(char* s)

{

    char* word_begin = NULL;

    char* temp = s;

    while (*temp) {

        if ((word_begin == NULL) && (*temp != ' ')) {

            word_begin = temp;

        }

        if (word_begin

            && ((*(temp + 1) == ' ')

                || (*(temp + 1) == ''))) {

            reverse(word_begin, temp);

            word_begin = NULL;

        }

        temp++;

    }

    reverse(s, temp - 1);

}

int main()

{

    char s[] = "i like this program very much";

    char* temp = s;

    reverseWords(s);

    printf("%s", s);

    return 0;

}

Java

import java.io.*;

class GFG {

  static void reverse(char[] str, int start, int end)

  {

    char temp;

    while (start <= end) {

      temp = str[start];

      str[start] = str[end];

      str[end] = temp;

      start++;

      end--;

    }

  }

  static char[] reverseWords(char[] s)

  {

    int word_begin = -1;

    int i = 0;

    while (i < s.length) {

      if ((word_begin == -1) && (s[i] != ' ')) {

        word_begin = i;

      }

      if (word_begin != -1

          && ((i + 1 == s.length)

              || (s[i + 1] == ' '))) {

        reverse(s, word_begin, i);

        word_begin = -1;

      }

      i++;

    }

    reverse(s, 0, (s.length - 1));

    return s;

  }

  public static void main(String[] args)

  {

    String s = "i like this program very much";

    char[] p = reverseWords(s.toCharArray());

    System.out.println(p);

  }

}

Python3

def reverse(str, start, end):

    temp = ''

    str1 = ""

    while (start <= end):

        temp = str[start]

        str[start] = str[end]

        str[end] = temp

        start+=1

        end-=1

    return str1.join(str)

def reverseWords(s):

    word_begin = -1

    i = 0

    while (i < len(s)):

        if ((word_begin == -1) and (s[i] != ' ')):

            word_begin = i

        if (word_begin != -1 and ((i + 1 == len(s)) or (s[i + 1] == ' '))):

            s = reverse(list(s), word_begin, i)

            word_begin = -1

        i+=1

    s = reverse(list(s), 0, (len(s) - 1))

    return s

s = "i like this program very much"

p = reverseWords(list(s))

print(p)

C#

using System;

class GFG

{

  static void reverse(char[] str, int start, int end)

  {

    char temp;

    while (start <= end) {

      temp = str[start];

      str[start] = str[end];

      str[end] = temp;

      start++;

      end--;

    }

  }

  static char[] reverseWords(char[] s)

  {

    int word_begin = -1;

    int i = 0;

    while (i < s.Length) {

      if ((word_begin == -1) && (s[i] != ' ')) {

        word_begin = i;

      }

      if (word_begin != -1

          && ((i + 1 == s.Length)

              || (s[i + 1] == ' '))) {

        reverse(s, word_begin, i);

        word_begin = -1;

      }

      i++;

    }

    reverse(s, 0, (s.Length - 1));

    return s;

  }

  static void Main(string[] args)

  {

    String s = "i like this program very much";

    char[] p = reverseWords(s.ToCharArray());

    Console.WriteLine(p);

  }

}

Javascript

function reverse(s, begin, end) {

    while (begin < end) {

        let charArray = [...s];

        let temp = charArray[begin];

        charArray[begin] = charArray[end];

        charArray[end] = temp;

        begin++;

        end--;

        s = charArray.join("");

    }

    return s;

}

function reverseWords(s) {

    let word_begin = -1;

    let i = 0;

    while (i < s.length) {

        if ((word_begin == -1) && (s[i] != ' ')) {

            word_begin = i;

        }

        if (word_begin != -1

            && ((s[i + 1] == ' ') || (i + 1 == s.length))) {

            s = reverse(s, word_begin, i);

            word_begin = -1;

        }

        i++;

    }

    s = reverse(s, 0, s.length - 1);

    return s;

}

let s = "i like this program very much";

s = reverseWords(s);

console.log(s);

Output

much very program this like i

Time Complexity: O(N)
Auxiliary Space: O(N) 

Approach: To solve the problem follow the below idea:

We can do the above task by splitting and saving the string in a reverse manner. 

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Run a for loop in reverse order to print the words accordingly 

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

int main()

{

    string s[] = { "i",       "like", "this",

                   "program", "very", "much" };

    string ans = "";

    for (int i = 5; i >= 0; i--) {

        ans += s[i] + " ";

    }

    cout << (ans.substr(0, ans.length() - 1)) << endl;

    return 0;

}

Java

public class ReverseWords {

    public static void main(String[] args)

    {

        String s[]

            = "i like this program very much".split(" ");

        String ans = "";

        for (int i = s.length - 1; i >= 0; i--) {

            ans += s[i] + " ";

        }

        System.out.println(

            ans.substring(0, ans.length() - 1));

    }

}

Python3

s = "i like this program very much"

words = s.split(' ')

string = []

for word in words:

    string.insert(0, word)

print(" ".join(string))

C#

using System;

public class ReverseWords {

    public static void Main()

    {

        string[] s

            = "i like this program very much".Split(' ');

        string ans = "";

        for (int i = s.Length - 1; i >= 0; i--) {

            ans += s[i] + " ";

        }

        Console.Write(ans.Substring(0, ans.Length - 1));

    }

}

Javascript

<script>

var s= ["i", "like", "this", "program", "very", "much"];

    var ans ="";

    for (var i = 5; i >= 0; i--)

    {

        ans += s[i] + " ";

    }

    document.write(ans.slice(0,ans.length-1));

</script>

Output

much very program this like i

Time Complexity: O(N)
Auxiliary Space: O(N) 

Reverse words in a given string using the swap operation:

The above task can also be accomplished by splitting the words separately and directly swapping the string starting from the middle.

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Swap the words with each other starting from the middle
  • Print the string

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

string RevString(string s[], int l)

{

    if (l % 2 == 0) {

        int j = l / 2;

        while (j <= l - 1) {

            string temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    else {

        int j = (l / 2) + 1;

        while (j <= l - 1) {

            string temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    string S = s[0];

    for (int i = 1; i < 6; i++) {

        S = S + " " + s[i];

    }

    return S;

}

int main()

{

    string s = "i like this program very much";

    string words[]

        = { "i", "like", "this", "program", "very", "much" };

    cout << RevString(words, 6) << endl;

    return 0;

}

Java

import java.io.*;

class GFG {

    public static String[] RevString(String[] s, int l)

    {

        if (l % 2 == 0) {

            int j = l / 2;

            while (j <= l - 1) {

                String temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        else {

            int j = (l / 2) + 1;

            while (j <= l - 1) {

                String temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        return s;

    }

    public static void main(String[] args)

    {

        String s = "i like this program very much";

        String[] words = s.split("\s");

        words = RevString(words, words.length);

        s = String.join(" ", words);

        System.out.println(s);

    }

}

Python3

def RevString(s, l):

    if l % 2 == 0:

        j = int(l/2)

        while(j <= l - 1):

            s[j], s[l - j - 1] = s[l - j - 1], s[j]

            j += 1

    else:

        j = int(l/2 + 1)

        while(j <= l - 1):

            s[j], s[l - 1 - j] = s[l - j - 1], s[j]

            j += 1

        return s

s = 'i like this program very much '

string = s.split(' ')

string = RevString(string, len(string))

print(" ".join(string))

C#

using System;

class GFG {

    static string RevString(string[] s, int l)

    {

        if (l % 2 == 0) {

            int j = l / 2;

            while (j <= l - 1) {

                string temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        else {

            int j = (l / 2) + 1;

            while (j <= l - 1) {

                string temp;

                temp = s[l - j - 1];

                s[l - j - 1] = s[j];

                s[j] = temp;

                j += 1;

            }

        }

        string S = s[0];

        for (int i = 1; i < 6; i++) {

            S = S + " " + s[i];

        }

        return S;

    }

    public static void Main()

    {

        string[] words

            = {  "i", "like", "this", "program", "very", "much" };

        string a = RevString(words, words.Length);

        Console.WriteLine(a);

    }

}

Javascript

<script>

function RevString(s, l)

{

    if (l % 2 == 0)

    {

        let j = parseInt(l / 2, 10);

        while (j <= l - 1)

        {

            let temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    else

    {

        let j = parseInt((l / 2), 10) + 1;

        while (j <= l - 1)

        {

            let temp;

            temp = s[l - j - 1];

            s[l - j - 1] = s[j];

            s[j] = temp;

            j += 1;

        }

    }

    let S = s[0];

    for(let i = 1; i < 9; i++)

    {

        S = S + " " + s[i];

    }

    return S;

}

let s = "i like this program very much";

let words = [  "i", "like", "this", "program", "very much"];

document.write(RevString(words, 9));

</script>

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(N)

Reverse words in a given string using constant space:

Follow the below steps to solve the problem:

  • Go through the string and mirror each word in the string, 
  • Then, in the end, mirror the whole string.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

string reverse_words(string s)

{

    int left = 0, i = 0, n = s.size();

    while (s[i] == ' ')

        i++;

    left = i;

    while (i < n) {

        if (i + 1 == n || s[i] == ' ') {

            int j = i - 1;

            if (i + 1 == n)

                j++;

            while (left < j)

                swap(s[left++], s[j--]);

            left = i + 1;

        }

        if (i > left && s[left] == ' ')

            left = i;

        i++;

    }

    reverse(s.begin(), s.end());

    return s;

}

int main()

{

    string str = "i like this program very much";

    str = reverse_words(str);

    cout << str;

    return 0;

}

Java

import java.io.*;

class GFG {

    public static String swap(String str, int i, int j)

    {

        char ch[] = str.toCharArray();

        char temp = ch[i];

        ch[i] = ch[j];

        ch[j] = temp;

        return new String(ch);

    }

    public static String reverse_words(String s)

    {

        int left = 0, i = 0, n = s.length();

        while (s.charAt(i) == ' ')

            i++;

        left = i;

        while (i < n) {

            if (i + 1 == n || s.charAt(i) == ' ') {

                int j = i - 1;

                if (i + 1 == n)

                    j++;

                while (left < j)

                    s = swap(s, left++, j--);

                left = i + 1;

            }

            if (i > left && s.charAt(left) == ' ')

                left = i;

            i++;

        }

        s = new StringBuilder(s).reverse().toString();

        return s;

    }

    public static void main(String[] args)

    {

        String str

            = "i like this program very much";

        str = reverse_words(str);

        System.out.println(str);

    }

}

Python3

def reverse_words(s):

    left = 0

    i = 0

    s = list(s)

    n = len(s)

    while(s[i] == ' '):

        i = i+1

    left = i

    while(i < n):

        if(i+1 == n or s[i] == ' '):

            j = i-1

            if i+1 == n:

                j = j+1

            while left < j:

                s[left], s[j] = s[j], s[left]

                left = left+1

                j = j-1

            left = i + 1

        if(i > left and s[left] == ' '):

            left = i

        i = i+1

    s = ''.join(s)

    s = s[::-1]

    return s

s1 = "i like this program very much"

s1 = reverse_words(s1)

print(s1)

C#

using System;

class GFG {

    public static string swap(string str, int i, int j)

    {

        char[] ch = str.ToCharArray();

        char temp = ch[i];

        ch[i] = ch[j];

        ch[j] = temp;

        return new String(ch);

    }

    public static string reverse_words(string s)

    {

        int left = 0, i = 0, n = s.Length;

        while (s[i] == ' ')

            i++;

        left = i;

        while (i < n) {

            if (i + 1 == n || s[i] == ' ') {

                int j = i - 1;

                if (i + 1 == n)

                    j++;

                while (left < j)

                    s = swap(s, left++, j--);

                left = i + 1;

            }

            if (i > left && s[left] == ' ')

                left = i;

            i++;

        }

        char[] charArray = s.ToCharArray();

        Array.Reverse(charArray);

        return new string(charArray);

    }

    public static void Main(string[] args)

    {

        string str = "i like this program very much";

        str = reverse_words(str);

        Console.WriteLine(str);

    }

}

Javascript

function swap(s,a,b)

{

    let charArray = [...s];

    let temp = s[a];

    charArray[a] = s[b];

    charArray[b] = temp;

    return charArray.join("");

}

function reverse(str) {

    let charArray = [...str];

    let ans = "";

    for(let i=charArray.length-1;i>=0;i--)

    {

        ans+=charArray[i];

    }

    return ans;

 }

function reverse_words(s)

{

    let left = 0, i = 0, n = s.length;

    while (s[i] == ' ')

        i++;

    left = i;

    while (i < n) {

        if (i + 1 == n || s[i] == ' ') {

            let j = i - 1;

            if (i + 1 == n)

                j++;

            while (left < j)

            {

                s = swap(s,left++, j--);

            }

            left = i + 1;

        }

        if (i > left && s[left] == ' ')

            left = i;

        i++;

    }

    s = reverse(s);

    return s;

}

let str = "i like this program very much";

str = reverse_words(str);

console.log(str);

Output

much very program this like i

Time complexity: O(N)
Auxiliary Space: O(1)

Reverse words in a given string using constant space: using the slicing method and join functions:

Below is the implementation of the above approach:

Java

import java.util.*;

class GFG {

    public static void main(String[] args)

    {

        String text

            = "i like this program very much";

        String str[] = text.split(" ");

        Collections.reverse(Arrays.asList(str));

        System.out.println(String.join(" ", str));

    }

}

Python3

string = "i like this program very much"

s = string.split()[::-1]

print(" ".join(s))

PHP

<?php

$string = "i like this program very much";

$array = explode(" ", $string);

$rarray = array_reverse($array);

echo $newstring = implode(" ", $rarray);

?>

C#

using System;

using System.Linq;

public class GFG {

    static public void Main()

    {

        string text

            = "i like this program very much";

        Console.WriteLine(

            string.Join(" ", text.Split(' ').Reverse()));

    }

}

Javascript

        let text= "i like this program very much";

        let str = text.split(" ");

        str.reverse();

        str = str.join(" ");

        console.log(str);

C++

#include<bits/stdc++.h>

using namespace std;

int main() {

    string text = "i like this program very much";

    vector<string> str;

    istringstream iss(text);

    for (string s; iss >> s;) {

        str.push_back(s);

    }

    reverse(str.begin(), str.end());

    cout << str[0];

    for (int i = 1; i < str.size(); i++) {

        cout << " " << str[i];

    }

    return 0;

}

Output

much very program this like i

Time complexity: O(N2)
Auxiliary Space: O(N)

Approach: Without splitting the string

By this approach, we can even remove extra trailing spaces and in between the words also.

Basically, this algorithm involves 3 steps.

If you find white space, there can be two possibilities. 
It might be end of a word or else extra trailing space in between the words.
if it is not a white space, add the character to temporary word as shown in the below code.

Java

import java.util.*;

class GFG {

    public static String reverseString(String s)

    {

        StringBuilder ans=new StringBuilder();

        String temp = "";

        for(int i=0;i<s.length();i++)

        {

            char ch = s.charAt(i);

            if(ch==' ')

            {

                if(!temp.equals(""))

                {

                    ans.insert(0,temp+" ");

                }

                temp = "";

            }

            else

                temp += ch;

        }

        return ans.toString().substring(0,ans.length()-1);

    }

    public static void main(String[] args) {

        String s1=" Welcome to Geeks For Geeks ";

        System.out.println("Before reversing length of string : "+s1.length());

        String ans1=reverseString(s1);

        System.out.println("After reversing length of string : "+ans1.length());

        System.out.println("""+ans1+""n");

        String s2=" I Love Java   Programming     ";

        System.out.println("Before reversing length of string : "+s2.length());

        String ans2=reverseString(s2);

        System.out.println("After reversing length of string : "+ans2.length());

        System.out.println("""+ans2+""");

    }

}

Output

Before reversing length of string : 28
After reversing length of string : 26
"Geeks For Geeks to Welcome"

Before reversing length of string : 28
After reversing length of string : 24
"Programming     Java Love I"

Time Complexity: O(N) where N is length of string

Auxiliary Space: O(1) 

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

In this article we will write the formula to reverse the word order within a string in Microsoft Excel. We will use LEFT, RIGHT, LEN and FIND functions.

LEFT will help to pick the character  from the left side within a cell.

RIGHT will help to pick the character from the right side within a cell text.

LEN function we use to return the text length to a cell.

FIND function returns the location number at which a specific character or text string is first found, reading left to right (not case-sensitive).

Let’s take an example to understand how reversing the word order within a string.

Example 1: We have a list of Names in Column “A” and we need to show the name in its reverse order.

img5

Follow the below given steps:-

  • Select the cell B2, write the formula.
  • =RIGHT(A2,LEN(A2)-FIND(» «,A2))&» «&LEFT(A2,FIND(» «,A2)-1)
  • Press Enter on your keyboard.
  • The function will reverse the word order within a string.

img6;

  • To copy the formula to all the cells, press the key  “CTRL + C”  and select the cell B3 to B6 and press the key “CTRL + V”  on your keyboard.

img7

This is how we can reverse the order of the words by using the Right, Len, Find and Left functions in Microsoft Excel.

image 48

If you liked our blogs, share it with your friends on Facebook. And also you can follow us on Twitter and Facebook.
We would love to hear from you, do let us know how we can improve, complement or innovate our work and make it better for you. Write us at info@exceltip.com

ToggleCase cuts out all the hassle of having to retype words when you want to reverse the order. Simply type or paste the sentence you want to convert into the form below, hit the magic Reverse Words button and that’s it. Then just copy and paste your Reverse Words text to use elsewhere. Easy!

Have fun with ToggleCase and create Reversed Words messages online to suit all your needs. The great thing about ToggleCase is it’s quick, easy, web-based, free, and completely awesome! To demonstrate the true power of ToggleCase here’s an example of some Reversed Words text you can create in just seconds, not donkey’s years.

Transform from this chunk of text in sentence case:

ToggleCase is the coolest website ever! Where have you been all my life

To this chunk of text in reversed word order:

life my all been you have Where ever! website coolest the is ToggleCase

C program to reverse order of words in a given string – In this article, we will discuss the multiple methods to reverse the order of words in a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The methods used in the same are as follows:

  • Using Standard Method
  • Using Function

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

As given in the example in the uploaded image above, firstly, we need to enter a specific string.

The string uploaded is as follows:

“hello welcome to computer programming”

Thus, a completely reversed string of the same is as follows:

“programming computer to welcome hello”

Hence, the methods to do the same in C programming are as follows:

Using Standard Method

  1. Initialize k=0, j=0.

2) Read the entered string using gets(s). Initialize n=length of the string.

3) Swap the starting index element s[i] with the last index element s[n-i-1].Repeat this step using for loop for(i=0;i<n/2;i++).After all iterations of for loop, we will get reverse ordered string.

4) Insert the location values of the white spaces present in the string, in the array a[] using for loop for(i=0;s[i];i++) , by increasing i,k values.

After for loop initialize a[k] with i value.

5) Reverse the order of letters of each word in the reverse ordered string as

The outer for loop iterates with the structure for(i=0; i<=k;i++)

a) initialize n=a[i]-j.n indicates the length of the word.

b) The inner for loop iterates through the word with  the structure for(l=0;l<n/2;l++)

swap the element with starting index(l+j) with element with ending index (n-l-1) by increasing the l value.

Repeat a,b steps until i<=k.

6) Print the string with reverse order of words.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000];  

    int a[1000],i,n,k=0,j=0,l,temp;

    printf(«Enter  the string : «);

    gets(s);

    n=strlen(s);

    for(i=0;i<n/2;i++)  

    {

     temp=s[i];

s[i]=s[n1i];

s[n1i]=temp;

}

for(i=0;s[i];i++)

{

        if(s[i]==‘ ‘)

        {

  a[k++]=i;   

    }

    }

    a[k]=i;

    for(i=0;i<=k;i++)

{

n=a[i]j;

for(l=0;l<n/2;l++)

{

temp=s[l+j];

s[l+j]=s[a[i]1l];

s[a[i]1l]=temp;

}

j=a[i]+1;

}  

    printf(«n %s»,s);

    return 0;

}

Output:

Enter  the string: hello welcome to computer programming

programming computer to welcome hello

Using Function

  1. The swap(char *s1, char *s2) function swaps the character at the pointer variable s1 with the character at the pointer variable s2.

2) The stringlength(char *s) function will return the length of the given string.

3) The main() function calls the reverse(char *s) function, passing the string as an argument to the function. The reverse() function reverses the order of the words in the string.

4) The reverse() function calls the stringlength() function to get the length of the string and initialize the length value to n.

a) Calls the stringlength() function to get the length of the string and initialize the length value to n.

b) For loop iterates, through the string from i=0 to i<n/2.

It calls the swap() function to swap the element at starting index i with the element at last index (n-i-1).

The reverse function calls the swap function repeatedly until i<n/2.After all iterations of for loop, we will get the reverse ordered string.

c) It finds the locations of the white space in the string and stores the location values into the string a[] using for loop for(i=0;s[i];i++) and with increasing i, k values.

d) For loop iterates from i=0 to i<k

Initialize n with the length of the word.i.e a[i]-j.

The reverse function calls the swap function to swap the letter at the starting index (l+j) of the word with the letter at the last index (a[i]-l-1).

Initialize j=a[i]+1.

It calls the swap function repeatedly until i<k.

After all iterations of for loop, we will get the string with reverse ordered words.

5) Print the string with reverse order of words.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

#include <stdio.h>

#include <string.h>

swap(char *s1,char*s2)

{

char temp;

temp=*s1;

*s1=*s2;

*s2=temp;

}

int stringlength(char *s)

{

int i;

for(i=0;s[i];i++);

return i;

}

int reverse(char *s)

{

    int a[1000],i,n,k=0,j=0,l;

    n=stringlength(s);

    for(i=0;i<n/2;i++)  

    {

     swap(&s[i],&s[n1i]);

    }

for(i=0;s[i];i++)

{

        if(s[i]==‘ ‘)

        {

  a[k++]=i;   

    }

    }

    a[k]=i;

    for(i=0;i<=k;i++)

{

n=a[i]j;

for(l=0;l<n/2;l++)

{

swap(&s[l+j],&s[a[i]1l]);

        }

j=a[i]+1;

}  

}

int main()

{

    char s[1000];  

    printf(«Enter  the string : «);

    gets(s);

    reverse(s);

    printf(«n %s»,s);

}

Output:

Enter the string: hello welcome to computer programming

programming computer to welcome hello

Понравилась статья? Поделить с друзьями:
  • Reverse the text in word
  • Reverse the text in excel
  • Reverse the string word by word in java
  • Reverse print in word
  • Reverse ordering in excel