Error With Swapping Two Words from a String (Reverse)

I'm trying to output the two words in a string in reverse order.
For example, if the first word in the string is "Baseball" then the second word is "Basketball".
I want the output to be "Basketball Baseball".

The problem I have with this is that the program returns the answer with a space at the beginning.
I get something like this = " Basketball Baseball"

I don't want that space. I tried using "\b" and that doesn't work.

1
2
for (int i = 0; i < ch.length() / 2; i++)
		switch(ch[i], ch[ch.length() - i - 1]);


Is there a way to fix this within the loop or is there a way for me to do it in "cout"?
Why are you manipulating characters when <string>'s are much more powerful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

int main()
{
    std::string string1 = "baseball";
    std::string string2 = "basketball";
    
    std::string combined = string1 + ' ' + string2;
    std::cout << combined << '\n';
    
    std::string reversed;
    
    // BONUS
    for(int i = 0; i < combined.length(); i++)
        reversed += combined[combined.length() - i - 1];
    
    std::cout << reversed << '\n';
        
    
    return 0;
}
Last edited on
I don't want to have multiple strings. I know how to do it that way. I want to be able to make the user enter two word separated with a space then I can swap them.

The problem is the for loop. Yours doesn't work on my program neither. The one I showed gives me the closest answer, but it just adds that extra space at the beginning.
The standard library is your friend.

1
2
3
4
5
6
7
auto transpose_word(std::string::iterator beg, std::string::iterator end)
{
  auto const beg_word2 = 
    std::rotate(beg, std::find_if(beg, end, ::isspace), end);
  return 
    std::rotate(beg, std::find_if(beg, end, std::not_fn(::isspace)), beg_word2);   
}


Live demo:
http://coliru.stacked-crooked.com/a/29081000d4fb70f8
None of this helps with a “manipulate a string (array)” homework.

@joe809
I do not see anything weird or wrong with your code (excepting you typed “switch” instead of “swap” or whatever you used to exchange characters).

I suspect there is something amiss with your input method. Can I see that?
The problem is greater now. I was getting closer into fixing it, but it looks worse. I just simply want to return back both input lines. The program is just returning all of the words from the string in different order.

1
2
3
4
5
6
7
8
9
10
Input: Hello World
       New Day
Expected Output:
olleH dlroW
weN yaD

My Output:
  olleH weN
dlroW
yaD


I know the problem is in the swap() function. I have no idea how to fix it as I have tried several methods and done some tweakings.
Last edited on
Here's our two words separated and without leading blanks. The rest follows easily whatever the array xy problem is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// FINALLY ...
#include <iostream>
#include <cstring>

int main()
{
    char buffer[200];
    strcpy(buffer, "baseball basketball");
    
    size_t sz = strlen(buffer);
    
    size_t blank_position = 0;
    bool found{false};
    
    char part_1[200], part_2[200];
    for(size_t i = 0; i < sz; i++)
    {
        if(buffer[i] == ' ')
        {
            blank_position = i;
            found = true;
        }
        
        if(!found)
            part_1[i] = buffer[i];
        else
            part_2[i - blank_position - 1] = buffer[i];
    }
    
    part_1[blank_position] = '\0';
    part_2[sz - blank_position - 1] = '\0';
    
    std::cout
    << '*' << part_1 << "*\n"
    << '*' << part_2 << "*\n";
    
    return 0;
}


*baseball*
*basketball*
Program ended with exit code: 0


EDIT: Or alternatively depending on system - http://coliru.stacked-crooked.com/a/303188883a5171da
Last edited on
PS Before I forget, the challenge now is to do it in a single loop which is the obvious and probably simple refinement I have got time for at the moment.

ternary operator probably promising here.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void transpose( istream &in )
{
   string word;
   if ( in >> word )
   {
      transpose( in );
      cout << word << ' ';
   }
}

int main()
{
   for ( string line : { "Baseball Basketball", "hopeless", "", "  this   is an   awkward    test" } )
   {
      stringstream ss( line );
      transpose( ss );
      cout << '\n';
   }
}
@lastchance. Without denigrating you valiant attempt at sensible and mature programming <strings> of any sort aren't acceptable in this xyz problem.

Of course feel free to take the 1st, dare I say it, poll position because unlike the 'fatuous' present here, I am driven by pride and the greater good but not by my ego and self-aggrandizement - a trait we have in common despite the different paths.
againtry wrote:
<strings> of any sort aren't acceptable in this xyz problem.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cctype>

void transpose( const char *p )
{
   const int MAXCHARS = 80;
   char buffer[MAXCHARS+1];

   while ( isspace( *p ) ) p++;
   if ( !(*p) ) return;

   int i = 0;
   while( (*p) && !isspace( *p ) && i < MAXCHARS ) buffer[i++] = *p++;
   buffer[i] = 0;
   transpose( p );
   std::cout << buffer << ' ';
}

int main()
{
   transpose( "Baseball   Basketball Cricket    Rounders" );
}
Last edited on
Valiant++ :)
Another way could be to reverse the string as a whole, then reverse back individual words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;

void backwards( char arr[], int first, int last )
{
   while( first < last ) swap( arr[first++], arr[last--] );
}

void transpose( char line[] )
{
   int size = strlen( line );

   // Reverse the whole line
   backwards( line, 0, size - 1 );

   // Now reverse back individual words
   char *p = line;
   while ( true )
   {
      while( isspace( *p ) ) p++;
      if ( !( *p ) ) return;

      char *q = p + 1;
      while( ( *q ) && !isspace( *q ) ) q++;

      backwards( line, p - line, q - 1 - line );
      p = q;
   }
}

int main()
{
   char line[] = "Baseball Basketball";
   cout << line << '\n';
   transpose( line );
   cout << line << '\n';
}


Baseball Basketball
Basketball Baseball
Last edited on
.
Last edited on
I managed to fix it by using the code from this link,
https://www.geeksforgeeks.org/remove-extra-spaces-string/

Now, the only problem I am getting is the both lines are getting returned in the same line.
For example,
Expected Output:
Baskbetall Baseball
Soccer Football

My Output:
Football Soccer Baseball Basketball

I believe the problem might be in the while loop inside of the if ("word"). Maybe it's in the swap() function. I can't tell because if I try to change anything inside of those two, the output changes but incorrectly.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

string transpose( const string &line )
{
   string result;
   stringstream ss( line );
   for ( string word; ss >> word; ) result = word + ' ' + result;
   if ( !result.empty() ) result.resize( result.size() - 1 );
   return result;
}

int main()
{
   stringstream in( "The     owl    and the    pussy-cat went    to  sea  \n"
                    "In a beautiful pea-green boat\n"
                    "They took some money and plenty of honey\n"
                    "Wrapped up in a five-pound note\n" );
   for ( string line; getline( in, line ); ) cout << transpose( line ) << '\n';
}


sea to went pussy-cat the and owl The 
boat pea-green beautiful a In 
honey of plenty and money some took They 
note five-pound a in up Wrapped 
Last edited on
Topic archived. No new replies allowed.