is there a way to check if a String contains one of the item in array? like this:
dim txt as String="badword1 you! you son of a badword2!!"
dim Badwords() as String = {"badword1","badword2","badword3"}
if txt.contains(Badwords()) then
'Whoa.. txt contains some bad vibrations..
end if
I could use a loop but is there maybe a faster method how I can check a string if it contains one of the strings in the array?
I think this should do what you want
Dim txt As String = "badword1 you! you son of a badword2!!"
Dim Badwords() As String = {"badword1", "badword2", "badword3"}
If Badwords.Any(Function(b) txt.ToLower().Contains(b.ToLower())) Then
'Whoa.. txt contains some bad vibrations..
MessageBox.Show("You said a naughty word :P")
End If
You'll need to Import System.Linq
A loop is the simplest way.
However, if you are concerned about speed rather than legibility, you could replace the whole array with a single regular expression.
I'm not that good with Basic syntax (a bit rusty), but something like...
dim badwords as Regex = new Regex("badword1|badword2|badword3");
if badwords.IsMatch(txt) then
If the list of words is fixed, it would be best to make badwords a static. (Is that what they are called in Basic? I mean a variable which is only initialised once in the life of the program, not every time it is used.) There is a Compiled flag you can set in the Regex constructor which would speed things up even further (the expression is compiled when it is created, rather than when it is used).
Regex is found in the System.Text.RegularExpressions namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With