Search code examples
c++cstringreversewords

How to reverse all words in a string? C++


So.. I'm sorry I doubleposted. I really didn't know how this site works. However, I'm changing my whole question here so that it's more understandable. And here it is:

char s[1002];
cin.getline(s, 1002, '\n');
int k;
int p = strlen(s);
strcat(s, " ");

for (int i = 0; i <= p; i++)
{
    if (s[i] == ' ')
    {

        for (k = i - 1; (k != -1) && (s[k] != ' '); k--)
            cout << s[k];
        cout << " ";

    }
}

' ' , ',' , '.' and ';' should be delimiters but I've managed to pull it to work only with ' ' (intervals).

I cannot use std::string as I'm doing this for a homework where I need to make a very specific function - char const* reverseWordsOnly(const char*).

What should the code do?

Input: Reversing the  letters, is; really hard.

Output: gnisreveR eht  srettel, si; yllaer drah.

Solution

  • While I still feel this is a duplicate, the thought process for solving this would be this:

    1. Write a function that returns true for alphabet characters (a-z and A-Z), and false otherwise.
    2. Start at the beginning of the string
    3. Find the next alphabet character, note its location (start)
    4. Find the next non-alphabet character, note its location (end)
    5. Reverse the characters in the range [start, end)
    6. Repeat steps 3-5 until the end of the string

    All of this becomes very easy when you use std::string and algorithms like std::reverse instead of using raw arrays and custom. Since you are allowed to use std::cin and std::cout (<iostream>), the argument against using <string> is a silly one.