Search for strings

S

Sorin Sandu

I want to find if a string var is equal with a number of strings.
Something like var1 IN (or ==) "string1", "string2", "string3", ....
Which is the best method?
 
J

Jon Skeet [C# MVP]

Sorin Sandu said:
I want to find if a string var is equal with a number of strings.
Something like var1 IN (or ==) "string1", "string2", "string3", ....
Which is the best method?

A hashtable, perhaps?
 
M

Mike


Depends what your def'n of best is, and when the strings get their values
and if they're const.
For best == least code, try:
(string1+string2...).IndexOf(var1) >= 0
which over-matches and is slow as it is but may do what you want for nice
hacky test-code.

Or:
foreach( s in new string[] { "string1", var2, "string3"} )
if ( var1.Equals(s)) { found=true; break; }

(Of course, do the 'new' only once if you can help it.)

The hashtable's great advice for a varible # of items and/or lot's of items.

m
 
J

Jon Skeet [C# MVP]

Mike said:
Depends what your def'n of best is, and when the strings get their values
and if they're const.
For best == least code, try:
(string1+string2...).IndexOf(var1) >= 0
which over-matches and is slow as it is but may do what you want for nice
hacky test-code.

No, that fails in two ways. Suppose we're trying to find "needle". It
doesn't appear in either of these sets:

"aneedlea" "foo"

or

"nee" "dle"

- but both of them would match.
 
C

cody

For best == least code, try:
No, that fails in two ways. Suppose we're trying to find "needle". It
doesn't appear in either of these sets:

"aneedlea" "foo"

But he could do

(string1+":"+string2+":"...).IndexOf(var1) >= 0

to avoid the problem.

However, such an approach wins the "sloppy, stupid and slow award" in any
case :)

Searching in ArrayList, Hashtable or using a switch will be better.
 
M

Mike

Jon Skeet said:
No, that fails in two ways. Suppose we're trying to find "needle". It
doesn't appear in either of these sets:

"aneedlea" "foo"

or

"nee" "dle"

- but both of them would match.

That's why I said (emphasis added):
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top