Software & Finance





Visual C++ - Reversing the words in the line





The source code for reversing the words in the line is given on this page.

 


Source Code


#include <string>

#include <vector>

#include <map>

#include <set>

 

bool mystrreverse(char *buf, int len)

{

    int l = (len/2);

    if((len % 2) == 1)

        l++ ;

    for(int i = 0; i < l; i++)

    {

        // swap first and last character

        char ch = buf[i];

        buf[i] = buf[len - 1 - i];

        buf[len - 1 - i] = ch;

    }

    return true;

}

 

std::vector<std::pair<int, int> > ptrs;

 

{

 

    std::cout << "Input String: \t\t\t\t" << buf << "\n";

    int len = strlen(buf);

    int spos = 0;

    int l = 0;

 

    char *p = new char [len];

 

    for(int i = 0; i < len; i++)

    {

        if(buf[i] == ' ')

        {

            ptrs.push_back(std::pair<int, int>(spos, l + 1));

            spos = i + 1;

            l = 0;

        }

        else

            l++;

    }

   

    for(std::vector<std::pair<int, int> >::const_reverse_iterator it = ptrs.rbegin();

        ;

        ++it)

    {

        if(it == ptrs.rend())

            break;

        std::pair<int, int> v = (*it);

        strncpy(p, &buf[v.first], v.second);

        p +=  v.second;

    }

    p -= len;

    strcpy(buf, p);

    buf[len-1] = '\0';

    delete p;

 

    spos = 0;

    l = 0;

 

    std::cout << "After Words Reverse: \t\t\t" << buf << "\n";

 

    for(int i = 0; i < len; i++)

    {

        if(buf[i] == ' ' || i == len - 1)

        {

            mystrreverse(&buf[spos], l);

            spos = i + 1;

            l = 0;

        }

        else

        {

            l++;

        }

    }

 

    std::cout << "After Characters in Words Reverse:\t" << buf << "\n";

   

    mystrreverse(buf, strlen(buf));

 

    std::cout << "After complete line reverse: \t\t" << buf << "\n";

    return true;

}

   

void main()

{

    ///// line reverse

    char line[128] = "This is for testing ";

    mylinereverse(line);

}

 

 

Output


 

Input String:                           This is for testing

After Words Reverse:                    testing for is This

After Characters in Words Reverse:      gnitset rof si sihT

After complete line reverse:            This is for testing