I am trying to reverse a sentence contained in a string and return a string in the quickest way possible using the least amount of memory. Also I don't want to use any unsafe code, so no pointers are allowed. Please let me know if anything can be improved.
My input example is
string mystring = "Hello! my name is";
My result is
"is name my Hello!"
My results on i7 4770S for 1000000 iterations is on average around 650ms.
public static string ReverseTheString(string MyString)
{
int Length = MyString.Length;
Char[] NormalArray = new char[Length];
Char[] FinalArray = new char[Length];
for (int i = 0; i < Length; i++)
{
NormalArray[i] = MyString[i];
}
Length = Length - 1; //use for last index
int SpacesCount = 0;
int AlphaCount = 0;
Stack<char[]> ReversedArray = new Stack<char[]>();
for (int i = 0; i < NormalArray.Length; i++)
{
if (NormalArray[i] == ' ' && i != Length)//Space
{
if (i != Length)
{
if (AlphaCount > 0)
{
char[] temparray = new char[AlphaCount];
int tempindex = i - AlphaCount;
for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
{
temparray[k] = NormalArray[j];
}
ReversedArray.Push(temparray);
AlphaCount = 0;
temparray = null;
}
SpacesCount++;
}
else
{
SpacesCount++;
if (SpacesCount > 0)
{
char[] temparray = new char[SpacesCount];
int tempindex = i + 1 - SpacesCount;
for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
{
temparray[k] = NormalArray[j];
}
ReversedArray.Push(temparray);
SpacesCount = 0;
temparray = null;
}
}
}
if (NormalArray[i] != ' ' ) //alpha
{
if (i != Length)
{
if (SpacesCount > 0)
{
char[] temparray = new char[SpacesCount];
int tempindex = i - SpacesCount;
for (int j = tempindex, k = 0; k < SpacesCount; j++, k++)
{
temparray[k] = NormalArray[j];
}
ReversedArray.Push(temparray);
SpacesCount = 0;
temparray = null;
}
AlphaCount++;
}
else
{
AlphaCount++;
if (AlphaCount > 0)
{
char[] temparray = new char[AlphaCount];
int tempindex = i + 1 - AlphaCount;
for (int j = tempindex, k = 0; k < AlphaCount; j++, k++)
{
temparray[k] = NormalArray[j];
}
ReversedArray.Push(temparray);
AlphaCount = 0;
temparray = null;
}
}
}
}
int Pos = 0;
while (ReversedArray.Count > 0)
{
char[] temparray = ReversedArray.Pop();
for (int j = 0; j < temparray.Length; j++)
{
FinalArray[Pos] = temparray[j];
Pos++;
}
}
return new string(FinalArray);
}