I was tasked with using C++ to turn this
"Hello Jarryd, do you like socks?"
into:
"socks? like you do Jarryd, Hello";
Edit: The condition was to reverse this in place.
Here's what I came up with, knocked up in Visual Studio using the TestExplorer to run it. Criticism is much appreciated!
.h
namespace SentenceFlipNamespace
{
class SentenceFlip
{
public:
SentenceFlip();
~SentenceFlip();
int FlipSentenceInPlace(char* in_Sentence);
void SentenceFlip::Move(int in_StartIndex, char in_String[]);
};
}
.cpp
namespace SentenceFlipNamespace
{
SentenceFlip::SentenceFlip()
{
}
SentenceFlip::~SentenceFlip()
{
}
int SentenceFlip::FlipSentenceInPlace(char in_Sentence[])
{
int index = 0;
int length = strlen(in_Sentence);
while (index < length)
{
int dist = 0;
int wordSize = 0;
//Get the characters to the first word
for (int i = length - 1; i > 0; i--)
{
if (in_Sentence[i] == ' ' && i != length - 1)
{
dist = i - index;
wordSize = length - i - 1; //exclude the space
break;
}
}
//Push everything forwards
for (int i = 0; i <= dist; i++)
Move(index, in_Sentence);
//This leaves a space at the end, push it forward
if (index + wordSize >= length)
return 0;
for (size_t i = 0; i < length - wordSize - index - 1; i++)
Move(index + wordSize, in_Sentence);
index += wordSize + 1; //include the space
}
return -1;
}
void SentenceFlip::Move(int in_StartIndex, char in_String[])
{
char temp = in_String[in_StartIndex];
int length = strlen(in_String);
for (int j = length - 1; j >= in_StartIndex; j--)
{
char temp2 = in_String[j];
in_String[j] = temp;
temp = temp2;
}
}
}
Test Method, since I don't invoke it in main.
namespace CodeChallengesTests
{
TEST_CLASS(TextFlip)
{
public:
TEST_METHOD(SentenceFlipInPlace)
{
SentenceFlipNamespace::SentenceFlip *testFlip = new SentenceFlipNamespace::SentenceFlip();
char input[] = "Hello Jarryd, do you like socks?";
char expectedResult[] = "socks? like you do Jarryd, Hello";
testFlip->FlipSentenceInPlace(input);
Assert::AreEqual(expectedResult, input, "Results do not match");
}
};
}