Given a string, Reverse every word in the string in place. For example if you have Ayman Ali, running the algorithm should result in namyA ilA.
Solutions
Solutions
//Reverse words in string
var input = "ayman ali";
input += " ";
//Convert into Array
var arr = input.ToCharArray();
//Loop Through the array with the length of the array
var b = 0; //Pointer to an actual element
var e = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == ' ') //Space reached
{
e = i - 1;
//Rotate in place
for (int p = b; p < e - ((e-b) / 2); p++)
{
var temp = arr[p];
var m = e - (p - b);
arr[p] = arr[m];
arr[m] = temp;
}
b = e + 2;
}
}
//If first element note b = Begin of new word
//IF space or end of string
// Record the position as end of word (e)
// Rotate the word beginning with b and ending with e
// let b = e + 2
//Else
// Continue
//End Loop
//Rotate a word
//Loop through the word (Length half the word) begin with b and end with e
//Save Pointer element temporarily
//Save mirror position (m) into pointer position (p) - Define mirror position
//save p into m
Console.WriteLine(string.Join("",arr.Take(arr.Length-1)));
//Console.WriteLine(string.Join(",", out));
Console.ReadLine();
No comments:
Post a Comment