Search for strings

  • Thread starter Thread starter Sorin Sandu
  • Start date Start date
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?
 
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?
 

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
 
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.
 
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.
 
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):
 
Back
Top