Tuesday, May 22, 2007

Quick Tip: Search for strings within strings

It's time for another quick tip, this is for all you .NET fans out there. This tip helps you quick find a string within a string by simply using the IndexOf call, normally this is used to find the index location of where a specific starts but it can also be used to determine if a string pattern exist within a string at all, since the call will return a -1 if the pattern cannot be found in the string.

Here are a few examples:

VB.NET

Dim nStr as string = "what do you want now?"
'Check for "what"
if nStr.IndexOf("what")<>-1 Then
'You've got a "what" in your string
end if

C#

string nStr="what do you want now?"
//Check for "what"
if (nStr.IndexOf("what")!=-1)
{
//You've got a "what" in your string
}

No comments: