Last active
October 1, 2015 18:37
-
-
Save georgebearden/3e31331c733058ae8ca9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using System; | |
| using System.Diagnostics; | |
| using System.Linq; | |
| using System.Text; | |
| public class Program | |
| { | |
| public static string ReverseString(string input) | |
| { | |
| if (input == null) | |
| throw new InvalidOperationException("Cannot reverse a null string"); | |
| var values = input.ToArray<char>(); | |
| for (int i = 0; i < values.Length / 2; i++) | |
| { | |
| var start = values[i]; | |
| var end = values[values.Length - 1 - i]; | |
| values[i] = end; | |
| values[values.Length - 1 - i] = start; | |
| } | |
| return new string(values); | |
| } | |
| public static string ReverseWordsInString(string input) | |
| { | |
| if (input == null) | |
| throw new InvalidOperationException("Cannot reverse a null string"); | |
| var words = input.Split(' '); | |
| var reversed = new StringBuilder(); | |
| foreach (var word in words) | |
| { | |
| reversed.Append(ReverseString(word)).Append(" "); | |
| } | |
| return reversed.ToString().Trim(); | |
| } | |
| public static string ReverseWordsInStringLinqStyle(string input) | |
| { | |
| if (input == null) | |
| throw new InvalidOperationException("Cannot reverse a null string"); | |
| return input | |
| .Split(' ') | |
| .Aggregate(new StringBuilder(), (result, next) => result.Append(ReverseString(next)).Append(" ")) | |
| .ToString() | |
| .Trim(); | |
| } | |
| public static void Main(string[] args) | |
| { | |
| Debug.Assert(ReverseString("abcd") == "dcba"); | |
| Debug.Assert(ReverseString("abcde") == "edcba"); | |
| Debug.Assert(ReverseString("abcdef") == "fedcba"); | |
| Debug.Assert(ReverseString("abcdefg") == "gfedcba"); | |
| Debug.Assert(ReverseWordsInString("abcdefg") == "gfedcba"); | |
| Debug.Assert(ReverseWordsInString("a b c d") == "a b c d"); | |
| Debug.Assert(ReverseWordsInString("ab bc") == "ba cb"); | |
| Debug.Assert(ReverseWordsInStringLinqStyle("abcdefg") == "gfedcba"); | |
| Debug.Assert(ReverseWordsInStringLinqStyle("a b c d") == "a b c d"); | |
| Debug.Assert(ReverseWordsInStringLinqStyle("ab bc") == "ba cb"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment