CD Smith
CD Smith

Reputation: 6607

Check a string for containing a list of substrings

How can I check a specific string to see if it contains a series of substrings? Specifically something like this:

public GetByValue(string testString) {

    // if testString contains these substrings I want to throw back that string was invalid
    // string cannot contain "the " or any part of the words "College" or "University"

   ...
}

Upvotes: 0

Views: 358

Answers (5)

CD Smith
CD Smith

Reputation: 6607

Decided against checking for strings to limit my data return, instead limited my return to a .Take(15) and if the return count is more than 65,536, just return null

Upvotes: 0

Md Kamruzzaman Sarker
Md Kamruzzaman Sarker

Reputation: 2407

You can check it as follow....

   class Program
{



public static bool checkstr(string str1,string str2)
{
 bool c1=str1.Contains(str2);
 return c1;

}

public static void Main()
{
string st = "I am a boy";
string st1 = "boy";

bool c1=checkstr(st,st1);
//if st1 is in st then it print true otherwise false
      System.Console.WriteLine(c1);
}
}

Upvotes: 0

Assaf Lavie
Assaf Lavie

Reputation: 75983

This an interesting question. As @Jon mentioned, a regular expression might be a good start because it will allow you to evaluate multiple negative matches at once (potentially). A naive loop would be much less efficient in comparison.

Upvotes: 0

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

If performance is a concern, you may want to consider using the RegexStringValidator class.

Upvotes: 1

user1231231412
user1231231412

Reputation: 1659

You can use string.Contains() method

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

// This example demonstrates the String.Contains() method
using System;

class Sample 
{
public static void Main() 
{
string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
}

} /* This example produces the following results:

Is the string, s2, in the string, s1?: True */

Upvotes: 0

Related Questions