J.F.
J.F.

Reputation: 17

Q: C++ - Reversing a string (sentence and word) using a class

For my code, I am trying to create a class with two functions that:

  1. Display a cstring where each word is reversed

  2. Display an entire cstring reversed

My two test sentences are "Hi There" and "To Be", so the output is:

erehT iH
eB oT

iH erehT
oT eB

Here is my code:

#include <iostream>
#include <cstring>

using namespace std;

class cStringType {
public:
   char sentenceInput[80];  //Member variable
   void reverse_sentence();  //Member function
   void reverse_words();  //Member function
};  //Bottom of cStringType

int main()
{
    cStringType sentence1, sentence2;
    //Objects declared of cStringType

    cout << "Please enter a sentence!\n" << endl;
    cin.get(sentence1.sentenceInput, 79, '\n');

    cin.ignore(80, '\n');

    cout << "\nPlease enter another sentence!\n" << endl;
    cin.get(sentence2.sentenceInput, 79, '\n');

    cout << "\nThe first sentence reversed: ";
    sentence1.reverse_sentence();

    cout << endl;

    cout << "The second sentence where each word is reversed: ";
    sentence2.reverse_words();

    cout << endl;

    cout << endl;

    cout << "The first sentence where each word is reversed: ";
    sentence1.reverse_words();

    cout << endl;

    cout << "The second sentence reversed: ";
    sentence2.reverse_sentence();

    cout << endl;

    return 0;
}

void cStringType::reverse_sentence()
{
    char reverse_sentence;

    //Reverse entire sentence using loop
    for (int i = 0; i < strlen(sentenceInput) / 2; i++)
    {
       //Reverse the sentence using the length of the
       //variable in the class

       reverse_sentence = sentenceInput[i];
       //First get the user input
       //Set your variable equal to the variable in the class

       sentenceInput[i] = sentenceInput[strlen(sentenceInput) - i - 1];
       //Then reverse the characters and word order 
       //Starts from the last character in the array
       //and goes backwards to 0

       sentenceInput[strlen(sentenceInput) - i - 1] = reverse_sentence;
       //Set the variable equal to the result
       //sentenceInput is now the reverse of the user input in main
    }

    cout << sentenceInput << endl;
    //Output of the new sentence
}

void cStringType::reverse_words()
{
    int beginning, end, j = 0;
    char reverse_words;

    //Reverse each word separately using loop
    for (int i = 0; i <= strlen(sentenceInput); i++)
        //Get the length of the sentence in the class
    {
        if (sentenceInput[i] == ' ' || sentenceInput[i] == '\0')
            //Check for spaces or null characters
            //This allows only the letters of each word to be
            //reversed, not the entire sentence
        {
            for (beginning = j, end = i - 1;
                beginning < (i + j) / 2; beginning++, end--)
                //j is the beginning of the array; increases
                //i is the end of the array; decreases
            {
                reverse_words = sentenceInput[beginning];
                //Set a variable equal to the first 
                //word in the original user input

                sentenceInput[beginning] = sentenceInput[end];
                //Set the first letter of a word equal to
                //the last letter of a word

                sentenceInput[end] = reverse_words;
                //Set the result equal to the variable
                //sentenceInput is now the user input where each
                //word is reversed
            }
        }

        j = i + 1;
    }

    cout << sentenceInput << endl;
    //Output of the new sentence
}

When I try to run the code, the output becomes something like this:

Please enter a sentence!

Hi There

Please enter another sentence!

To Be

The first sentence reversed: erehT iH

The second sentence where each word is reversed: oT eB


The first sentence where each word is reversed: There Hi

The second sentence reversed: Be To

I tried fixing it, but to no avail. The output is never correct.

Is there some way to fix this issue? Or better yet, to simplify the code? I believe the issue is with the code in the function.

Upvotes: 0

Views: 910

Answers (2)

r3mus n0x
r3mus n0x

Reputation: 6144

The main problem with your code is that it's using the same buffer for both transformations. In other words: you are reversing the words in the same string which you've already reversed entirely. So you need to have another copy of the original string to do these independently.

Regarding simplifying your code you need to define a function that would reverse a string given a pointer and size or begin and end pointers. Then you can use this function on your entire string or on every word you find while searching for a space character:

char *begin = sentenceInput; //points to the beginning of the word
char *end = sentenceInput + strlen(sentenceInput);
for (char *it = begin; it != end; ++it)
    if (*it == ' ') {
        reverse(begin, it);
        begin = it + 1;
    }
reverse(begin, end); //reverse the last word

The reverse function can be either std::reverse, which can be used in the above code and on the entire string as follows:

std::reverse(sentenceInput, sentenceInput + strlen(sentenceInput))

or you can create a similar function like this:

void reverse(char *begin, char *end)
{
    --end; //point to the last character instead of one-past-last
    while (begin < end)
        std::swap(*begin++, *end--);
}

Upvotes: 1

MaikuZ
MaikuZ

Reputation: 56

I would suggest using stack for it, it is a natural way of looking at it.

so

#include <stack>

and then the function would be like that

void cStringType::reverse_words()
{
int beginning, end, j = 0;
char reverse_words;

stack<char> lastWord;
//Reverse each word separately using loop
for (int i = 0; i <= strlen(sentenceInput); i++)
    //Get the length of the sentence in the class
{
    if (sentenceInput[i] == ' ' || sentenceInput[i] == '\0')
        //Check for spaces or null characters
        //This allows only the letters of each word to be
        //reversed, not the entire sentence
    {
        //we want to print the last word that was parsed
        while(!lastWord.empty())
        {
            //we print in the reverse order the word by taking off the stack char by char
            cout<< lastWord.top();
            lastWord.pop();
        }
        cout<<" ";
    }
    //if the letter is not space or end of string then push it on the stack
    else
        lastWord.push(sentenceInput[i]);
    j = i + 1;
}

cout << sentenceInput << endl;
//Output of the new sentence
}

Upvotes: 0

Related Questions