diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 4488b595..a5cecf58 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -22,6 +22,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Strings - [Palindrome](src/Strings/palindrome.cs) - [Trie](src/Strings/trie.cs) +- [Character Limit](src/Strings/character-limit.cs) ## Search - [Binary Search](src/Search/binary-search.cs) diff --git a/algorithms/CSharp/src/Strings/character-limit.cs b/algorithms/CSharp/src/Strings/character-limit.cs new file mode 100644 index 00000000..b0b2719e --- /dev/null +++ b/algorithms/CSharp/src/Strings/character-limit.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; + +//Time Complexity: O(N) +namespace Algorithms.Strings +{ + public class TextHelper + { + public static void Main() + { + Console.WriteLine("Please enter a string"); + string input = Console.ReadLine(); + + while (input == "") + { + Console.WriteLine("Please enter a string"); + input = Console.ReadLine(); + } + + Console.WriteLine("Please enter the number of characters you want to show"); + string input2 = Console.ReadLine(); + + while (!input2.All(char.IsDigit) || input2.All(char.IsWhiteSpace)) + { + Console.WriteLine("The number you have entered is invalid. Please try again:"); + input2 = Console.ReadLine(); + } + + int num = Convert.ToInt32(input2); + Console.WriteLine(CharacterLimit(input, num)); + } + + //Limits the the amount of characters shown in a string. + public static string CharacterLimit(string input, int num) + { + //converts a string to a character array + char[] ch = input.ToCharArray(); + + //loops through the array from the last element to the first, and replaces each element with a "." + for (int i = ch.Count(); i > num; i--) + { + ch[i - 1] = '.'; + } + + //converts character array back to string to be returned by the method + string output = new string(ch); + return output; + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Strings/character-limit.cs b/algorithms/CSharp/test/Strings/character-limit.cs new file mode 100644 index 00000000..d810182b --- /dev/null +++ b/algorithms/CSharp/test/Strings/character-limit.cs @@ -0,0 +1,18 @@ +using NUnit.Framework; + +namespace Algorithms.CSharp.Test.Strings +{ + [TestFixture] + internal class Character_Limit + { + [TestCase("Hello", "Hel..")] + [TestCase("World", "Wor..")] + [TestCase("How Ya", "How...")] + [TestCase("Doin", "Doi.")] + public void PassString_ShouldGetExpectedResult(string text, string expected) + { + string result = Algorithms.Strings.TextHelper.CharacterLimit(text, 3); + Assert.AreEqual(expected, result); + } + } +} \ No newline at end of file