Last active
August 29, 2015 14:16
-
-
Save stanroze/47a1d3abe3719f2f7c5a to your computer and use it in GitHub Desktop.
Reverse string in place, wouldn't work for UTF-16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string ReverseWords(string text) | |
{ | |
var tarr = text.ToCharArray(); | |
//reverse the whole string first | |
reverse(tarr, 0, tarr.Length-1); | |
//reverse parts of the string | |
int start = 0; | |
for(int i = 0; i<tarr.Length; i++) | |
{ | |
if(tarr[i] == ' ') | |
{ | |
reverse(tarr, start, i -1); | |
while(i < tarr.Length && tarr[i] == ' ') | |
{ | |
i++; | |
} | |
start = i; | |
} | |
} | |
reverse(tarr,start,tarr.Length-1); | |
return new String(tarr); | |
} | |
public static void reverse(char[] text, int start, int end) | |
{ | |
if (start == end || start - end == 1) | |
return; | |
char tmp; | |
int steps = (end-start) / 2; | |
int step = 0; | |
int i = start; | |
int r = end; | |
while(step++ <= steps) | |
{ | |
tmp = text[i]; | |
text[i] = text[r]; | |
text[r] = tmp; | |
i++; | |
r--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment