-3

I have a string "this is a test". I want to reverse it to "test a is this". We will take one string as "This is a test". After reversing it string should be "test a is this"

#include <stdio.h>

char *reverse(char *p);
void main() {
    char p[100] = "this is a test";
    char *s = reverse(p);
    printf("%s", s);
}

output - test a is this.

ajay
  • 9,402
  • 8
  • 44
  • 71
sambit
  • 81
  • 2
  • 4
  • 4
    Read [the Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist). You might also want to learn what a [SSCCE](http://sscce.org/) is. – Some programmer dude Feb 16 '14 at 16:26
  • 2
    `void main`? also why c++ tag? – AliciaBytes Feb 16 '14 at 16:36
  • @Duck; Oops! Forgot about that. – haccks Feb 16 '14 at 16:39
  • @ajay Your edit removes a critical part of the question, "without using inbuilt function" in the title, and doesn't add that to the question. Sorry, but it is an invalid edit and I have to roll it back. – Matthew Lundberg Feb 16 '14 at 16:57
  • @MatthewLundberg I think there's no inbuilt function to do that. But anyway, I should have kept it. Sorry. – ajay Feb 16 '14 at 17:01
  • possible duplicate of [Reversing words in a sentence](http://stackoverflow.com/questions/3276582/reversing-words-in-a-sentence) – AShelly Feb 16 '14 at 21:55

6 Answers6

1

I would do it like this:

#include <boost/regex.hpp>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char*argv[]){
    string xStr;
    cin >> xStr;

    boost::regex xRegEx("(\\S+)");
    vector<string> words;

    boost::sregex_iterator xIt(xStr.begin(), xStr.end(), xRegEx);
    boost::sregex_iterator xInvalidIt;
    while(xIt != xInvalidIt)
        words.push_back( *xIt++ );

    for(std::vector<string>::iterator it = words.rbegin(); it != words.rend(); ++it) {
        cout << *it << " ";
    }

    return 0;
}
Vitaly Dyatlov
  • 1,872
  • 14
  • 24
1

You can use the following algorithm:

  1. Split the string into words in an array of strings (let's say A).
  2. Print A in reverse order.
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Emu
  • 5,763
  • 3
  • 31
  • 51
1

Here's a simple strategy to reverse the order of words in a string.

  • Reverse the string (sentence)
  • Reverse back each word in the string

Let's break down the task into the following functions:

int mystrlen(char *s);  // find the length of the string
char *rev_substr(char *s, int len);  // reverse the substring s of length len 
char *rev_sentence(char *s);  // reverse the order of words in the string s

Here are the function definitions:

int mystrlen(char *s) {
    int i = 0;
    while(*s) {
        i++;
        s++;
    }
    return i;
}

char *rev_substr(char *s, int len) {
    int i = 0; 
    int j = len - 1;
    char temp;
    while(i < j) {
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        i++;
        j--;
    }
    return s;
}

char *rev_sentence(char *s) {
    int i, j = 0;
    int len = mystrlen(s);
    rev_substr(s, len);  // reverse the whole string
    for(i = 0; i <= len; i++) {
        // a word is delimited by a space or the null character
        if(s[i] == ' ' || s[i] == '\0') {   
            rev_substr(s+j, i-j);  // reverse back each word
            j = i + 1;    // j is the index of the first letter of the next word
        }
    }
    return s;
}

A sample implementation:

int main(void) {
    char s[] = "this is a test";
    printf("%s\n", rev_sentence(s));
    return 0;
}
ajay
  • 9,402
  • 8
  • 44
  • 71
0

One way could be to split the sentence using a stringstream, and later just copy the words in reverse order:

std::string get_reversed( const std::string& str )
{
    std::stringstream input( ss );
    std::vector<std::string> temp;
    std::stringstream output;

    std::copy( std::istream_iterator<std::string>( input , " " ) ,        
               std::istream_iterator<std::string>() ,
               std::back_inserter( temp )
             );

    std::reverse_copy( std::begin( temp ) ,
                       std::end( temp ) ,
                       std::ostream_iterator<std::string>( output , " " )
                     );

    return output.str();        
}

No regular expressions, no Boost: Only Standard Library containers and algorithms ;)

Manu343726
  • 13,969
  • 4
  • 40
  • 75
0

Try this:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

char* reverseString(char* inStr)
{
    int numChars = strlen(inStr);             // Length of input string
    char* outStr = (char*)malloc(numChars+1); // Allocate 1 + string length so there is space to fit '\0' 
    char* wordStart = &inStr[numChars];       // Pointer to the start of a word. Initialized to '\0' character of the input
    char* wordEnd = wordStart-1;              // Pointer to the end of word. Initialized to the last character of the input
    char* destination = outStr;               // Pointer to the start of a new word in the reversed string
    char* srcStart;                           // Temporary pointer
    char  delimiter;                          // Word delimiter set to '\0' when the first word of input is copied, set to ' ' for 
                                              // all other words in the input string 
    while (--wordStart >= inStr)
    {
        if (*wordStart == ' ')
        {
            srcStart = wordStart+1;           // start at the first letter following the space    
            delimiter = ' ';                  // add a space at the end of the copied word
        }
        else if (wordStart == inStr)
        {
            srcStart = wordStart;             // start at the first letter of the input string
            delimiter = '\0';                 // add the null terminator to mark the end of the string 
        }
        else
        {
            srcStart = NULL;                  // not at word boundary, mark NULL so the logic below skips the copy operation
        }

        if (srcStart)
        { 
            for (char* src = srcStart; src <= wordEnd; ++src, ++destination)
            {
                *destination = *src;
            }
            *destination = delimiter;
            destination++;
            wordEnd = wordStart-1;
        }
    }

    return outStr;
}

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        cout << "Please provide an input string!..." << endl;
        return -1;
    }
    cout << "Original String = " << argv[1] << endl
         << "Reversed String = " << reverseString(argv[1]) << endl;

    return 0;   
}

This does incur the cost of creating a new string, so it's not the most efficient route, but it gets the job done.

DigitalEye
  • 1,456
  • 3
  • 17
  • 26
  • By the way, another limitation in the above implementation is that it doesn't handle periods at the end of a sentence correctly. – DigitalEye Feb 18 '14 at 20:52
0

A program that uses recursive calling.

int count=0;
void w_rev(char *p)
{
    if((*p)!= '\0')
    {
        if((*p) !=' ')
        {
            w_rev(p+1);
            printf("%c",*p);
        }
        count++;
    }
}
void w_rev_call(char * p)
{
    while(*(p+count) != '\0'  )
        {
            w_rev(p+count);
            printf(" ");
        }
}

If arr is the name of the array, then the statement w_rev_call(arr) will give desired output.

Frog
  • 311
  • 1
  • 10