-4

I am trying to write a c++ code that reverse a string by the user . ex :

the user enters "apple and orange" .

the output is "orange and apple" .

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

int main(void) {

char str[100];

char delims[] = " ";
char *token;

printf("enter your word seperated by space ");
gets(str);
token = strtok( str, delims );
while ( token != NULL ) {
    printf( " %s\n", token);
    token = strtok( NULL, delims );

}
system("pause");
return 0;
}

Q : how can I swap the first and the last word ? Thanks.

user3435095
  • 45
  • 2
  • 9

1 Answers1

0

Use std::string.

Use std::string::find to find the beginning and end of a word.

Use std::string::substr to copy the word to a new string.

Use std::stack<std::string> to contain the words.

Push each word into the stack.

At the end of the sentence:
pop word, print word.

Example:

// Input the sentence.
std::string word;
std::string sentence;
cout << "Enter sentence: ";
cout.flush();
std::getline(cin, sentence);

// Search for the end of a word.
static const char letters[] = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";
std::string::size_type word_start_position = 0;
std::string::size_type word_end_position = 0;
word_end_position = sentence.find_first_not_of(letters);
word = sentence.substr(word_start_position, 
                       word_end_position - word_start_position);

// Put the word into a stack
std::stack<std::string> word_stack;
word_stack.push_back(word).  

There are issues with this example, but it shows the fundamental concepts.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • I am not c++ programmer , please can you show me the code ? @ThomasMatthews – user3435095 May 10 '14 at 18:37
  • @user3435095: Updated answer. There are other techniques to extract the words, such as using `std::istringstream` and `std::getline`. However, the `std::getline` only allows one delimiter to mark the end of a word, and there are more characters that mark the end of a word, as this comment shows. – Thomas Matthews May 10 '14 at 18:49