0

I need to check if a string pattern in the array is contained in a string. I am using the following code but it matches the exact string contained in the array not the pattern so the following will fail. How can I do this?

String[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
String SearchString = "String1:sdfsfsdf";

 if (stringArrayToBlock.Contains(SearchString.Trim().ToLower()))
 { 
   //Do work
 }
5
  • isn't the condition the other way around? Commented Dec 3, 2012 at 7:17
  • by 'string pattern' you mean like '12345',so it should locate all strings which have 5 numbers ? Commented Dec 3, 2012 at 7:22
  • well it works this way because I need to check If the string in the array matches the string. But now that I am thinking of it I guess it is the same Commented Dec 3, 2012 at 7:23
  • Isn't this a regex issue then? Commented Dec 3, 2012 at 7:24
  • well I don't know how to use regex to work this around. Commented Dec 3, 2012 at 7:27

2 Answers 2

3

I guess you should do it vice versa. Besides, if you're open to LINQ, Enumerable.Any Method is very handy:

string[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
string SearchString = "String1:sdfsfsdf";
string lowerCaseString = SearchString.Trim().ToLower();
if (stringArrayToBlock.Any(s => lowerCaseString.Contains(s)))    
{
    //Do work
}
Sign up to request clarification or add additional context in comments.

Comments

3

Use the LINQ Any() method to determine if any of the elements of the array satisfy the condition. The Contains method used here is that of string, not of Array.

String[] stringArrayToBlock = { "#", "/", "string1:", "string2" };
String SearchString = "String1:sdfsfsdf";

 if (stringArrayToBlock.Any(s => SearchString.Trim().ToLower().Contains(s)))
 { 
     //Do work
 }

4 Comments

I'll quote Bryan Hong: isn't the condition the other way around?
I think the question is regarding locating 'string pattern' not the 'exact string'
yes I mention that I am looking for the string pattern, anyways, thank you
Sorry. Missed that part. Why am I getting upvotes? It's obviously wrong :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.