Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Using Contains with empty string
Message
De
18/07/2014 09:20:44
 
 
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Versions des environnements
Environment:
VB 9.0
OS:
Windows Server 2012
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01604011
Message ID:
01604017
Vues:
36
>>>Hi,
>>>
>>>I need to check if a string is within another string. Here is an example:
>>>
>>>
>>> if (!LongString.Contains(ShortString))
>>>    {
>>>           // do something
>>>    }
>>>
>>>
>>>The problem I have is when the short string (ShortString) is empty (""), "do something" never does anything. Of course I can get around the problem by adding to the IF ShortString.Length = 0 || . But I was wondering, can I change the .Contains somehow to make it work with empty string?
>>
>>Nothing you can do about how 'Contains' works. Maybe :
if (string.IsNullOrEmpty(ShortString) || !LongString.Contains(ShortString))
or you could get fancy and write your own extension method :-}
>
>This is what I thought when I said to add to the IF the expression checking for empty ShortString. And if you confirm that this is the optimal solution, then it is good enough for me.

If you need it a lot then:
public static bool DoesNotContain(this String str, string shortString)
        {
            return string.IsNullOrEmpty(shortString) || !str.Contains(shortString);
        }
then:
            if (LongString.DoesNotContain(ShortString))
            {
                //
            }
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform