473,837 Members | 1,620 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Contains for string?

Tom
Is there such a thing as a CONTAINS for a string variable in VB.NET? For
instance, I want to do something like the following:

If strTest Contains ("A","B", "C") Then
Debug.WriteLine ("Found characters")
Else
Debug.WriteLine ("Did NOT find characters!")
End If

Nov 21 '05
17 8165
Herfried,
Its harder with RegEx to check to see if it contains all
three...
Especially for longer strings, the way I propagate may be inefficient, but
I don't know how Regex is implemented...


Longer input or longer list of words?

RegEx has no syntax that states "this & that" per se (you would need to
create a convoluted pattern), it only has "this or that" (via "this|that" )
so checking for one of significant number of words with a regex is
relatively easy (see my other post). Checking for all of a list of words
with RegEx would be significantly hard!

As I've stated before, I would not worry about performance until the routine
was proven to be a performance problem. I would go with one of the two RegEx
I gave earlier based on if the list of words was static or dynamic... If the
RegEx proved to have a performance problem then I would replace the
Algorithm with a more efficient one... (if one could be found that was truly
more efficient in the context of the routine).

Hope this helps
Jay

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:eO******** ******@TK2MSFTN GP10.phx.gbl... Jay,

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> schrieb:
You raised an interesting question. Does Tom want to know
if strTest contains all three or one of?


First I tested if 'String' contains a 'Contains' method, but it doesn't
contain such a method.

BTW: My solution can be simply adapted by replacing 'AndAlso' with
'OrElse' in order to check for the occurance of one (or more) of the
substrings in the string.
Its harder with RegEx to check to see if it contains all
three...


Especially for longer strings, the way I propagate may be inefficient, but
I don't know how Regex is implemented...

Wondering too...

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 21 '05 #11
Tom
No, actually all I would want to know is if any of the strings exists in the
line. I want it to work pretty much the way the SQL IN verb works. i.e.
where Status in ('ACTIVE','OTHE R')

Which brings up an interesting question: Is there any kind of IN verb
anywhere in VB.NET or the .NET framework?

But thanks for all the suggestions; I think I will try to make up a function
or something that I can call to do this.

Tom

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:uQ******** *****@TK2MSFTNG P11.phx.gbl...
Herfried,
You raised an interesting question. Does Tom want to know if strTest
contains all three or one of?

Its harder with RegEx to check to see if it contains all three...

Wondering
Jay

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:OD******** ******@TK2MSFTN GP12.phx.gbl...
"Tom" <to*@nospam.com > schrieb:
Is there such a thing as a CONTAINS for a string variable in VB.NET? For instance, I want to do something like the following:

If strTest Contains ("A","B", "C") Then
Debug.WriteLine ("Found characters")
Else
Debug.WriteLine ("Did NOT find characters!")
End If


For reasons of readability, I prefer this solution:

\\\
Dim s As String = _
"Quidquid id est timeo Danaos et dona ferentes."
If _
InStr(s, "Quidquid") AndAlso _
InStr(s, "timeo") AndAlso _
InStr(s, "dona") _
Then
MsgBox("True")
Else
MsgBox("False")
End If
///

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>


Nov 21 '05 #12
Tom
Herfried: Yep, I can do it this way, and that is pretty much how I have been
doing it. I just thought there had to be some other intrinsic built-in way
of doing it without having to write the code. That would be a good function
to have in the .NET framework.

I wonder if using a RegEx or using your method would be faster?

Tom

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:eO******** ******@TK2MSFTN GP10.phx.gbl...
Jay,

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> schrieb:
You raised an interesting question. Does Tom want to know
if strTest contains all three or one of?
First I tested if 'String' contains a 'Contains' method, but it doesn't
contain such a method.

BTW: My solution can be simply adapted by replacing 'AndAlso' with

'OrElse' in order to check for the occurance of one (or more) of the substrings in
the string.
Its harder with RegEx to check to see if it contains all
three...
Especially for longer strings, the way I propagate may be inefficient, but

I don't know how Regex is implemented...

Wondering too...

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 21 '05 #13
Tom,

That is very easy that MVB "Instr" method is the fastest for finding
"strings", it outclasses all other methods.

We have made some testing in past about this in this newsgroup, here is the
thread

http://tinyurl.com/3z2nk

Cor

"Tom" <to*@nospam.com >
Herfried: Yep, I can do it this way, and that is pretty much how I have
been
doing it. I just thought there had to be some other intrinsic built-in way
of doing it without having to write the code. That would be a good
function
to have in the .NET framework.

I wonder if using a RegEx or using your method would be faster?

Tom

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:eO******** ******@TK2MSFTN GP10.phx.gbl...
Jay,

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> schrieb:
> You raised an interesting question. Does Tom want to know
> if strTest contains all three or one of?


First I tested if 'String' contains a 'Contains' method, but it doesn't
contain such a method.

BTW: My solution can be simply adapted by replacing 'AndAlso' with

'OrElse'
in order to check for the occurance of one (or more) of the substrings in
the string.
> Its harder with RegEx to check to see if it contains all
> three...


Especially for longer strings, the way I propagate may be inefficient,
but

I
don't know how Regex is implemented...

Wondering too...

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>


Nov 21 '05 #14
"Cor Ligthert" <no************ @planet.nl> schrieb:
That is very easy that MVB "Instr" method is the fastest for finding
"strings", it outclasses all other methods.

We have made some testing in past about this in this newsgroup, here
is the thread

http://tinyurl.com/3z2nk


I think the theoretically fastest implementation would be an adapted version
of the Boyer Moore algorithm or the KMP pattern matching algorithm. By
calling 'InStr' three times (for looking for the occurance of three strings
in the text) there may be comparisons done that don't need to be done with a
specialized implementation.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 21 '05 #15
Herfried,

I was thinking about just making a sample method as is the indexofArray and
than with strings, cannot be that hard when you everytime move the index of
a string one position and test it than against the string when the position
is less than the lenght of the search word.

Than would the instr be faster than the indexof, however it would be a
little bit strange routine when I would make this, because I would use the
substring instead of the Mid.

Both should be very easy to be done and probably be the fastest routine, and
when you are sure it are bytes and no unicodes even faster to be done with a
bytearray.

However with methods in previouw message I did mean all methods which are
standard in dotnet as regex, indexof, etc.

Cor

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at>

"strings", it outclasses all other methods.

We have made some testing in past about this in this newsgroup, here
is the thread

http://tinyurl.com/3z2nk


I think the theoretically fastest implementation would be an adapted
version of the Boyer Moore algorithm or the KMP pattern matching
algorithm. By calling 'InStr' three times (for looking for the occurance
of three strings in the text) there may be comparisons done that don't
need to be done with a specialized implementation.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 21 '05 #16
Tom,
As we all suggested there is no builtin "In" function per se.

I would use the RegEx as its IMHO the "simplest" & "cleanest"
implementation! However! you need to understand RegEx to be comfortable
using it, luckily this regex is easy. Also you may need to get over the
perception that RegEx is slow. Yes it has some inherit overhead the other
methods do not, however that overhead may be warranted for the simplicity of
the routine. Also based on the context the overhead of the RegEx may be
lower, significantly lower, then other routines.

Note: I would only use the RegEx method for checking Strings, if I was
creating an "In" for other types I would pick an algorithm that was more
friendly for that type.

Here's one possibility for an "In" function based on RegEx.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
Dim pattern As String = String.Join("|" , words)
Return System.Text.Reg ularExpressions .Regex.IsMatch( input, pattern)
End Function

Then to use it you simple need to:

strTest = "The cat jumped over the sleepy dog."
If [In](strTest, "cat","dog" , "sleep") Then
Debug.WriteLine ("Found strings")
Else
Debug.WriteLine ("Did NOT find strings!")
End If

If the above RegEx version proved to be a performance problem I would then
consider using a For Each loop.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
For Each word As String In words
If input.IndexOf(w ord) <> -1 Then
Return True
End If
Next
Return False
End Function

I would consider creating an object that contained a list of words, which
had a method the checked to see if a string had one of those words.

Public Class ValidValues

Private ReadOnly m_regex As System.Text.Reg ularExpressions .Regex

Public Sub New(ByVal ParamArray words() As String)
Dim pattern As String = String.Join("|" , words)
m_regex = New System.Text.Reg ularExpressions .Regex(pattern,
System.Text.Reg ularExpressions .RegexOptions.C ompiled)
End Sub

Public Function IsMatch(ByVal value As String) As Boolean
Return m_regex.IsMatch (value)
End Function

End Class
Dim values As New ValidValues("ca t", "dog", "sleep")
If values.IsMatch( strTest) Then
Debug.WriteLine ("Found strings")
Else
Debug.WriteLine ("Did NOT find strings!")
End If
Return

Dim statusValues As New ValidValues("AC TIVE","OTHER")
If statusValues.Is Match(Status) Then
...

Notice in both cases that the actual method (algorithm) of matching is
hidden (encapsulated) within either the object or the function itself. Which
allows you to replace the Algorithm with a more efficient one if needed...

Whether I used the Function or Class would depend on how the function or
class was being within my program... Using Refactoring
http://www.refactoring.com I can change between the two...

As the others pointed out there are other equally valid ways to implement
the above. There are also methods that have yet to be mentioned, such as
using a HashTable or using a DataSet, plus still others. Which one you
should use REALLY depends on the context of what you are doing!

For example if your status value is in a DataTable, you can use a filter
statement that include an "In" statement, on either DataTable.Selec t or
DataView.RowFil ter. Like wise of the list of valid statues are in a
DataTable, you could use DataTable.Rows. Find assuming that the status was
the primary key to that table, or use filter & either DataTable.Selec t or
DataView.RowFil ter...

Hope this helps
Jay


"Tom" <to*@nospam.com > wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
No, actually all I would want to know is if any of the strings exists in
the
line. I want it to work pretty much the way the SQL IN verb works. i.e.
where Status in ('ACTIVE','OTHE R')

Which brings up an interesting question: Is there any kind of IN verb
anywhere in VB.NET or the .NET framework?

But thanks for all the suggestions; I think I will try to make up a
function
or something that I can call to do this.

Tom

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:uQ******** *****@TK2MSFTNG P11.phx.gbl...
Herfried,
You raised an interesting question. Does Tom want to know if strTest
contains all three or one of?

Its harder with RegEx to check to see if it contains all three...

Wondering
Jay

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:OD******** ******@TK2MSFTN GP12.phx.gbl...
> "Tom" <to*@nospam.com > schrieb:
>> Is there such a thing as a CONTAINS for a string variable in VB.NET? For >> instance, I want to do something like the following:
>>
>> If strTest Contains ("A","B", "C") Then
>> Debug.WriteLine ("Found characters")
>> Else
>> Debug.WriteLine ("Did NOT find characters!")
>> End If
>>
>
> For reasons of readability, I prefer this solution:
>
> \\\
> Dim s As String = _
> "Quidquid id est timeo Danaos et dona ferentes."
> If _
> InStr(s, "Quidquid") AndAlso _
> InStr(s, "timeo") AndAlso _
> InStr(s, "dona") _
> Then
> MsgBox("True")
> Else
> MsgBox("False")
> End If
> ///
>
> --
> Herfried K. Wagner [MVP]
> <URL:http://dotnet.mvps.org/>



Nov 21 '05 #17
Tom
Thanks, Jay, this helped greatly.

Tom

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:u6******** ******@TK2MSFTN GP14.phx.gbl...
Tom,
As we all suggested there is no builtin "In" function per se.

I would use the RegEx as its IMHO the "simplest" & "cleanest"
implementation! However! you need to understand RegEx to be comfortable
using it, luckily this regex is easy. Also you may need to get over the
perception that RegEx is slow. Yes it has some inherit overhead the other
methods do not, however that overhead may be warranted for the simplicity of the routine. Also based on the context the overhead of the RegEx may be
lower, significantly lower, then other routines.

Note: I would only use the RegEx method for checking Strings, if I was
creating an "In" for other types I would pick an algorithm that was more
friendly for that type.

Here's one possibility for an "In" function based on RegEx.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
Dim pattern As String = String.Join("|" , words)
Return System.Text.Reg ularExpressions .Regex.IsMatch( input, pattern) End Function

Then to use it you simple need to:

strTest = "The cat jumped over the sleepy dog."
If [In](strTest, "cat","dog" , "sleep") Then
Debug.WriteLine ("Found strings")
Else
Debug.WriteLine ("Did NOT find strings!")
End If

If the above RegEx version proved to be a performance problem I would then
consider using a For Each loop.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
For Each word As String In words
If input.IndexOf(w ord) <> -1 Then
Return True
End If
Next
Return False
End Function

I would consider creating an object that contained a list of words, which
had a method the checked to see if a string had one of those words.

Public Class ValidValues

Private ReadOnly m_regex As System.Text.Reg ularExpressions .Regex

Public Sub New(ByVal ParamArray words() As String)
Dim pattern As String = String.Join("|" , words)
m_regex = New System.Text.Reg ularExpressions .Regex(pattern,
System.Text.Reg ularExpressions .RegexOptions.C ompiled)
End Sub

Public Function IsMatch(ByVal value As String) As Boolean
Return m_regex.IsMatch (value)
End Function

End Class
Dim values As New ValidValues("ca t", "dog", "sleep")
If values.IsMatch( strTest) Then
Debug.WriteLine ("Found strings")
Else
Debug.WriteLine ("Did NOT find strings!")
End If
Return

Dim statusValues As New ValidValues("AC TIVE","OTHER")
If statusValues.Is Match(Status) Then
...

Notice in both cases that the actual method (algorithm) of matching is
hidden (encapsulated) within either the object or the function itself. Which allows you to replace the Algorithm with a more efficient one if needed...

Whether I used the Function or Class would depend on how the function or
class was being within my program... Using Refactoring
http://www.refactoring.com I can change between the two...

As the others pointed out there are other equally valid ways to implement
the above. There are also methods that have yet to be mentioned, such as
using a HashTable or using a DataSet, plus still others. Which one you
should use REALLY depends on the context of what you are doing!

For example if your status value is in a DataTable, you can use a filter
statement that include an "In" statement, on either DataTable.Selec t or
DataView.RowFil ter. Like wise of the list of valid statues are in a
DataTable, you could use DataTable.Rows. Find assuming that the status was
the primary key to that table, or use filter & either DataTable.Selec t or
DataView.RowFil ter...

Hope this helps
Jay


"Tom" <to*@nospam.com > wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
No, actually all I would want to know is if any of the strings exists in
the
line. I want it to work pretty much the way the SQL IN verb works. i.e.
where Status in ('ACTIVE','OTHE R')

Which brings up an interesting question: Is there any kind of IN verb
anywhere in VB.NET or the .NET framework?

But thanks for all the suggestions; I think I will try to make up a
function
or something that I can call to do this.

Tom

"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message news:uQ******** *****@TK2MSFTNG P11.phx.gbl...
Herfried,
You raised an interesting question. Does Tom want to know if strTest
contains all three or one of?

Its harder with RegEx to check to see if it contains all three...

Wondering
Jay

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:OD******** ******@TK2MSFTN GP12.phx.gbl...
> "Tom" <to*@nospam.com > schrieb:
>> Is there such a thing as a CONTAINS for a string variable in VB.NET?

For
>> instance, I want to do something like the following:
>>
>> If strTest Contains ("A","B", "C") Then
>> Debug.WriteLine ("Found characters")
>> Else
>> Debug.WriteLine ("Did NOT find characters!")
>> End If
>>
>
> For reasons of readability, I prefer this solution:
>
> \\\
> Dim s As String = _
> "Quidquid id est timeo Danaos et dona ferentes."
> If _
> InStr(s, "Quidquid") AndAlso _
> InStr(s, "timeo") AndAlso _
> InStr(s, "dona") _
> Then
> MsgBox("True")
> Else
> MsgBox("False")
> End If
> ///
>
> --
> Herfried K. Wagner [MVP]
> <URL:http://dotnet.mvps.org/>



Nov 21 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
14339
by: Aleksi Kallio | last post by:
I want to say something like this: <xsl:if test="contains($my-string, {'banana', 'apple', 'lemon'})"> Ie. I want to do "contains" against many strings. I don't want to write them all manually to condition clause, because it's cumbersome and it would help a lot if those strings could be passed into template as a parameter. What would be the easiest way to do this?
2
2037
by: Piotr Szukalski | last post by:
Hi! I have trouble with 'Contains' method in ListViewItemCollection class - it seems like it nevers calls 'Equals' method of class inherited from ListViewItem... I've found that ListViewItem doesn't override 'Equals' method, but I _DO_ override it in my class. Have a look at thread:...
2
2670
by: Dot net work | last post by:
Hello, My simple code is here: Public Class MyDictionary Inherits System.Collections.DictionaryBase Private Class MyElement Public Overloads Overrides Function Equals(ByVal obj As Object) As Boolean End Function
13
14991
by: nishit.gupta | last post by:
Is their any fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" Thnx
14
21783
by: Ralf Rottmann \(www.24100.net\) | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some increasing LINQ evangelism down here in Germany.). Assume I want to select rows from a database and check whether a specific column contains keywords from a list of keywords. The following works just fine: List<stringsearchTerms = new List<string>() { "Maria", "Pedro" };
4
10287
by: Jeff | last post by:
Hey ..NET 3.5 I'm trying to search a string to determine if the string contains </table>, but string.Contains don't find it. I've used WebRequest/WebReponse to retrieve the html from a webpage and now I'm searching through this html... this webpage contains 4 html tables. so there are 4 </table>, but my code don't find any...
8
1379
by: Tanzen | last post by:
I'm working in visual studio 2005 trying to learn visual basic. Having come from an VB for Access background, I'm finding it a big learning curve. I have been working through several e-books which have shown how to use custom collections to store lists of data. I've coded the custom collection and before I add members to it, I want to use the contains method to ensure the data does not already exist in the collection. My play code is...
1
2056
by: Jon Skeet [C# MVP] | last post by:
On Apr 30, 3:56 pm, Raja <rajesh.mad...@gmail.comwrote: Well, in fact it's *not* working fine - it's not behaving the same on SQL server as it would be in normal code. String.Contains is case- sensitive. My guess is that your database is set to be case- insensitive, hence why it's behaving how you want it to. To get a case-insensitive Contains equivalent in normal code (which includes LINQ to XML - the delegate is being executed...
8
4666
by: SMJT | last post by:
Does anyone know why the string contains function always returns true if the token is an empty string? I expected it to return false. "AnyOldText".Contains("") or "AnyOldText".Contains(String.Empty)
0
9851
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10901
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10583
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10286
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9419
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7012
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5680
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3128
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.