Have you learned about using
Regular Expressions?
They are amazingly powerful...you describe what you are looking for based on a pattern and then ask the regular expression if anything in your input matches that pattern.
The
regular expression pattern syntax can get tricky sometimes...but your pattern would be really easy.
Your pattern would be: are there any characters in my input that match "This Set Of Special Characters".
If your "special characters" are just punctuation they would include:
- !"#$%&'()*+,-./:;<=>?@[\]^_`{|}
Some of those special characters are used in regular expression pattern syntax or they represent wild cards in regular expressions and so you need to negate them using the '\' character in your regular expression.
Anyways, in regular expressions if you want to match any character within a "set of characters" you simply have to put that set of characters within square brackets "[]".
So, for the regular expression to match any of the above "special characters" you would have:
-
Dim pattern As String = "[!""#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]"
(I have escaped out all of the wild cards and because the above code is for a VB.NET string I had to use the VB.NET escape code for the " character too).
That only matches punctuation characters though and your requirement includes "white space" as well.
In regular expression syntax the way to indicate that you are looking for white space (in .NET) is to use "\s".
So, we just add "\s" to the set (put it within the square brackets) and it should be the full pattern for what you are looking for:
-
Dim pattern As String = "[!""#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~\s]"
Now all you have to do is use regular expressions controls that .NET provides you to and ask it for anything in the input string that matches the regular expression:
-
Dim input As String = "Hi! Hello, How are you?"
-
Dim pattern As String = "[!""#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~\s]"
-
Dim matches As MatchCollection = Regex.Matches(input, pattern)
-
MessageBox.Show(String.Format("There are {0} special characters in the input '{1}'", matches.Count, input))
The topic of regular expressions can get pretty complicated but it is truly amazing because regular expressions can accomplish so much in a very elegant way.
I mean, look at what you had to do to accomplish this task without regular expressions...you needed loops, functions to check characters, counters etc etc..
And look at what you have to do to accomplish this using regular expressions: a well thought out pattern and one function call.
Look through the links I posted and use google to research this more. Take your time with this topic because it's complicated.
Ask for help with it (I'm not a huge expert on regular expressions but I can usually get by when asked to do something) and definitely ask your teacher to properly cover this topic because it's too big to cover here.
-Frinny