Learn Computer Science programming - C# and C++ Algorithms

 

Flip Words

Flip words. Here is the logic:
  • Create variable
  • Start at strLen(a) original string
  • While until readPos-- is space or 0
  • Set Word Start o ReadPos +1
  • Copy Word to new array (WordStart - WordEnd)
  • Place a space in new array
  • Assign WordEnd = ReadPos
  • Add a null termination
  • Copy new array into old array
Code
flip_words.zip
File Size: 2299 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;


void FlipWords ()
{
wcout <<  endl << "*** Flip words  ***" << endl;
wcout << "*************************************************" << endl;

char a[] = "Tom Hanks";
cout << endl << "a= " << a << endl;
char* b = new char[strlen(a)+1];
int ReadPos, WordEnd, WordStart, WritePos = 0;
ReadPos = WordEnd = strlen(a) -1;

while (ReadPos >= 0)
{
while((a[ReadPos] != ' ') && (ReadPos >= 0))
ReadPos--;

WordStart=ReadPos +1;

while(WordStart <= WordEnd)
b[WritePos++] = a[WordStart++];

// Add space
if (ReadPos >= 0) 
b[WritePos++] = a[ReadPos--];

WordEnd = ReadPos;
}

b[WritePos] = '%%CONTENT%%';
strcpy(a, b);
delete b;
cout << endl << "a= " << a << endl; // Tom Hanks
}


void main()
{
int x;
// -----------------------------------------------------------------------
wcout <<  endl << "*** Flip words in a string ***" << endl;
wcout << "*************************************************" << endl;
FlipWords ();
cin >> x;
 }