Reverse a String

As you can see from this one, it's a few decades old. But hey, it works. Pulled it from the deep dark recesses of my archives.

Back to Code Samples

class ConsoleApp
{
[STAThread]
unsafe static void Main(string[] args)
{
if (args.Length > 0)
{
byte[] Bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(args[0]);

fixed ( byte* pBytes = &Bytes[0] )
{
// Reverse the string.
Reverse(pBytes, (args.Length > 1));
}

Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(Bytes));

}
}

unsafe static void Reverse(byte* SrcString, bool ReverseWords)
{
int iStart = 0
,iEnd = 0
,iLength = 0
;

// Get the length of the string.
while (SrcString[iLength] != '\0')
iLength++;

ReverseString(SrcString, iStart, iLength - 1);

if (ReverseWords)
{
while (iEnd < iLength)
{
if (SrcString[iEnd] != ' ')
{
iStart = iEnd;

// Find the next non-word character.
while(iEnd < iLength && SrcString[iEnd] != ' ')
iEnd++;

ReverseString(SrcString, iStart, --iEnd);
}

iEnd++;
}
}
}

unsafe static void ReverseString(byte* SrcString, int Start, int End)
{
byte Temp;

while (End > Start)
{
Temp = SrcString[Start];
SrcString[Start++] = SrcString[End];
SrcString[End--] = Temp;
}
}
}

Back to Code Samples