Search
 
SCRIPT & CODE EXAMPLE
 

C

code to reverse the words in a sentnce

/**
 * C program to reverse order of words in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[100], reverse[100];
    int len, i, index, wordStart, wordEnd;

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

    len   = strlen(str);
    index = 0;

    // Start checking of words from the end of string
    wordStart = len - 1;
    wordEnd   = len - 1;

    while(wordStart > 0)
    {
        // If a word is found
        if(str[wordStart] == ' ')
        {
            // Add the word to the reverse string
            i = wordStart + 1;
            while(i <= wordEnd)
            {
                reverse[index] = str[i];

                i++;
                index++;
            }
            reverse[index++] = ' ';

            wordEnd = wordStart - 1;
        }

        wordStart--;
    }

    // Finally add the last word
    for(i=0; i<=wordEnd; i++)
    {
        reverse[index] = str[i];
        index++;
    }

    // Add NULL character at the end of reverse string
    reverse[index] = ''; 

    printf("Original string 
%s

", str);
    printf("Reverse ordered words 
%s", reverse);

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
C :: temperature sensor data 
C :: false and true in c 
C :: input multipal data types 
C :: reading arrays from stdin c 
C :: YOUNG SEX PARTY underground collection 
C :: Uri/Beecrowd Problem no - 1184 solution in C 
C :: Program to Find Swap Numbers Using Temporary Variable 
C :: Clearing The Input Buffer In C/C++ 
C :: pre-commit configuration 
C :: write a c program to find out ncr factor of given number 
C :: WARNING: QA Issue: rdepends on 
C :: C linked sorted lists 
C :: command line coursera 
C :: %d and %i 
C :: passage on dowry 
C :: unconstrained box flutter 
C :: c printf affichage 
C :: bit wise operation 
C :: Sampoo C programming 
C :: c arrays 
C :: how to push node using linked list c 
Dart :: flutter delay 
Dart :: flutter text right overflowed 
Dart :: flutter border around textbutton 
Dart :: hide keyboard flutter 
Dart :: flutter clear all text in textfield 
Dart :: scaffold background color gradient 
Dart :: cross icon flutter 
Dart :: dart move item in list 
Dart :: RenderFlex overflowed 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =