Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top