Introduction
This post is an extension to a previous post about an extension method I had written for counting the number of times all words appear in the string.For example, the word "extension" appeared twice in the sentence above.
If you haven't read it, then you will find it here
In this article, I would like to share the RemoveSpecialCharacters extension method.
String.RemoveSpecialCharacters
The purpose of this method is to strip out certain characters from a string. But only if they occur on the outside of what we consider to be a word.For example, these words might appear in a string "Xmas!" and "Xmas". The subtle difference being that one word has an exclamation mark and the other hasn't, but they are both the same word. However, special characters within the word will not be excluded and so if we have the following words appearing in the string: "they're" and "theyre" then the method will not strip out the apostrophe because it is part of the word and so will consider these words to be different. (Even though the second word isn't really a word...)
Below is the signature:
public static string RemoveSpecialCharacters(this string text, char[] invalidCharacters) text is the string we wish to perform this functionality on. invalidCharacters are the characters we wish to exclude. For example: new char[] { '.', ',', '!', '?', '\'', '"', ';' }Firstly, we loop over each invalid character and find the index of it withing the string.
foreach (var c in invalidCharacters) { var charIndex = text.IndexOf(c);
Now this is where it gets a little tricky.
Invalid characters may appear in a variety of ways within a string (and that is why unit tests are crucial to proving your logic works! I have included my unit tests at the bottom of this post). The text may appear like the following:
1. "a cat sat on the mat"
2. "a cat sat on the mat!"
3. "a, cat, sat, 'on' the, mat!"
The code is written to attempt to handle these three situations.
The first situation is covered as no specified special character appears in this string.
The second situation has only one special character and that appears at the end of the string with no spaces before or after this character.
The third situation has many special characters occuring throughout the string, plus the character at the end.
And remember, we don't want to exclude characters that occur within the word!
And now you understand these scenarios, let's continue onto the code.
Here, we have an initial check on the character index, we want to check that it exists within the string and also if it appears at the end of the string. If this is true, we remove it.
if (charIndex != -1 && charIndex + 1 == text.Length) { text = text.Remove(text.IndexOf(c), 1); }
However, if the character actually occurs somewhere within the string then we want to check if it is surrounded with a space either before or after it's index. For example, " word! " a space appears after the exclamation mark and so we wish to remove this. However, if this was the case " wor!d " then we won't remove it, as we must assume that the writer is young, hip and uses 1nt3rn37 5p34ch.
We use a while loop to ensure that we check all occurances of this character within the string and we remove the unwanted characters.
You may have spotted some duplicate code during this while loop (and yes, I am ashamed). After we remove the character, we then get the index of the next occurrence of this character and then we check if it is the last character in the string and if so, we remove it. This is so that we can remove the last unwanted character within the string.
while (charIndex != -1 && (text.Substring(charIndex - 1, 1).Equals(" ") || text.Substring(charIndex + 1, 1).Equals(" "))) { text = text.Remove(text.IndexOf(c), 1); charIndex = text.IndexOf(c); // If the last character it finds is at the end of the string if (charIndex != -1 && charIndex + 1 == text.Length) { text = text.Remove(text.IndexOf(c), 1); } }
But as I'm aspiring to be a good developer and a decent human being, I will spend more time scratching my head over this as duplicate code always leaves a bitter taste. The issue here is that this condition occurs in the while loop that also occurs within the else block of the intial condition that we are duplicating (Does this make sense?). I am sure the fault is to do with the design of the code and perhaps changing the approach will sort this out, but let's see...
In the meantime, if this article remains unchanged, then I hope you have the brains to figure this out and would like to share it with me.
Take care.
Here is the full code:
public static string RemoveSpecialCharacters(this string text, char[] invalidCharacters) { foreach (var c in invalidCharacters) { var charIndex = text.IndexOf(c); // If the characters index is at the end of the string. if (charIndex != -1 && charIndex + 1 == text.Length) { text = text.Remove(text.IndexOf(c), 1); } else { // Remove charcaters only if they are next to a space. (e.g. " 'Hello' ") while (charIndex != -1 && (text.Substring(charIndex - 1, 1).Equals(" ") || text.Substring(charIndex + 1, 1).Equals(" "))) { text = text.Remove(text.IndexOf(c), 1); charIndex = text.IndexOf(c); // If the last character it finds is at the end of the string if (charIndex != -1 && charIndex + 1 == text.Length) { text = text.Remove(text.IndexOf(c), 1); } } } } return text; }
Unit Tests
[TestMethod] public void Test_WordCounter_GetWordCounts_6() { Dictionary<string, int> resultWords = new Dictionary<string, int>() { {"a",1}, {"cat",1}, {"sat",1}, {"on",1}, {"the",1}, {"mat",1}, }; string test = "a cat sat on the mat"; Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); CollectionAssert.AreEquivalent(resultWords, words); } [TestMethod] public void Test_WordCounter_GetWordCounts_7() { Dictionary<string, int> resultWords = new Dictionary<string, int>() { {"a",1}, {"cat",1}, {"sat",1}, {"on",1}, {"the",1}, {"mat",1}, }; string test = "a cat sat on the mat!"; Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); CollectionAssert.AreEquivalent(resultWords, words); } [TestMethod] public void Test_WordCounter_GetWordCounts_8() { Dictionary<string, int> resultWords = new Dictionary<string, int>() { {"a",1}, {"cat",1}, {"sat",1}, {"on",1}, {"the",1}, {"mat",1}, }; string test = "a, cat, sat, 'on' the, mat!"; Dictionary<string, int> words = test.GetWordCounts(false, new char[] { '.', ',', '!', '?', '\'', '"', ';' }); CollectionAssert.AreEquivalent(resultWords, words); }
No comments:
Post a Comment