Reverse Word Wise

Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is.

Input format :
String in a single line
Output format :
Word wise reversed string in a single line
Constraints :
0 <= |S| <= 10^7
where |S| represents the length of string, S.
Sample Input 1:
Welcome to Coding Ninjas
Sample Output 1:
Ninjas Coding to Welcome
Sample Input 2:
Always indent your code
Sample Output 2:
code your indent Always



 #include <iostream>

#include "solution.h"

using namespace std;

#include<string.h>

int lenght(char str[]){

    int count=0;

    for (int i=0;str[i]!='\0';i++){

        count++;

    }

    return count;

}


void reverseStringWordWise(char str[]) {

    { 

    int length = strlen(str); 

  

    // Traverse string from end 

    int i; 

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

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

  

            // putting the NULL character at the  

            // position of space characters for 

            // next iteration.          

            str[i] = '\0'; 

  

            // Start from next charatcer      

            printf("%s ", &(str[i]) + 1); 

        } 

    } 

  

    // printing the last word 

     

}

int main() {

    char input[1000];

    cin.getline(input, 1000);

    reverseStringWordWise(input);

    cout << input << endl;

}


https://www.geeksforgeeks.org/print-words-string-reverse-order/



#include <iostream>

// Write your code here

    int len=lenght(input);

    int i=0;

    int j=len-1;

    

    while(i<j){

        char temp=input[i];

        input[i]=input[j];

        input[j]=temp;

        i++;

        j--;

    }

     i=0;

     j=0;

    for(i=0;i<lenght(input);i++){

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

            while((i-1)>j-1){

            char temp=input[i-1];

            input[i-1]=input[j-1];

            input[j-1]=temp;

            i--;

            j++;

                

        }

        j=j+i+1;

  i=j;

        

            

        

    }

int main() {

    // Write C++ code here

    std::cout << "Hello world!";


    return 0;

}


Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings