here is my code ....i use in C#. that's my interview question.
using System.Collections.Generic;
using System.Text;
namespace ReverseString
{
class ReverseStringAdjactionWord
{
//reverses text in between two integer;
private static void Swap(char[] charArray,int p1, int p2)
{
while (p1 < p2)
{
char temp;
//swap
temp = charArray[p1];
charArray[p1] = charArray[p2];
p1++;
charArray[p2] = temp;
p2--;
}
}
//
// reverses the complete string
public static void ReverseString(char[] s)
{
//1.basic empty
if (s == null) return;
//2. find two word
if (s.Length > 0)
{
//c1 and c2 will point to the first word, and c3 and c4 will point to the second word
int c1, c2, c3, c4, c5, c6,c7;
c1 = c2 = c3 = c4 = 0;
//below code will find two word and reverse them....show
while (c4 < s.Length)
{
//find the first word--------------------------
for (; c1 < s.Length && s[c1] == ' '; c1++, c2++) ;//handle multiple spaces between words
if (c1 >= s.Length) break;
for (; c2 < s.Length && s[c2] != ' '; c2++) ;
//find the second word
c3 = c4 = c2;
for (; c3 < s.Length && s[c3] == ' '; c3++, c4++) ;//handle multiple spaces between words
if (c3 >= s.Length) break;
for (; c4 < s.Length && s[c4] != ' '; c4++) ;
//reverse the string from c1 to c4-1
c5 = c6 = c1;
c7 = c4-1;
Swap(s, c1, c7);
//---------------------------- these code reverse two word
//next, reverse word by word
while (c6 <= c7)
{
//handle multiple spaces between words
for (; c5 <= c7 && s[c5] == ' '; c5++, c6++) ;
if (c5 > c7) break;
// find word boundary
for (; c6 <= c7 && s[c6] != ' '; c6++) ;
Swap(s, c5, c6 - 1);
c5 = c6;
}
c1 = c2 = c3 = c4;
}
}
}
}
}