C# string does not contain possible?
I'm looking to know when a string开发者_如何学C does not contain two strings. For example.
string firstString = "pineapple"
string secondString = "mango"
string compareString = "The wheels on the bus go round and round"
So, I want to know when the first string and second string are not in the compareString.
How?
This should do the trick for you.
For one word:
if (!string.Contains("One"))
For two words:
if (!(string.Contains("One") && string.Contains("Two")))
You should put all your words into some kind of Collection or List and then call it like this:
var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");
bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));
If you need to make a case or culture independent search you should call it like this:
bool containsAnySearchString =
searchFor.Any(word => compareString.IndexOf
(word, StringComparison.InvariantCultureIgnoreCase >= 0);
So you can utilize short-circuiting:
bool containsBoth = compareString.Contains(firstString) &&
compareString.Contains(secondString);
Use Enumerable.Contains function:
var result =
!(compareString.Contains(firstString) || compareString.Contains(secondString));
bool isFirst = compareString.Contains(firstString);
bool isSecond = compareString.Contains(secondString );
Option with a regexp if you want to discriminate between Mango
and Mangosteen
.
var reg = new Regex(@"\b(pineapple|mango)\b",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (!reg.Match(compareString).Success)
...
The accepted answer, and most others will present a logic failure when an unassociated word contains another. Such as "low" in "follow". Those are separate words and .Contains
and IndexOf
will fail on those.
Word Boundary
What is needed is to say that a word must stand alone and not be within another word. The only way to handle that situation is using regular expressions and provide a word boundary \b
rule to isolate each word properly.
Tests And Example
string first = "name";
var second = "low";
var sentance = "Follow your surname";
var ignorableWords = new List<string> { first, second };
The following are two tests culled from other answers (to show the failure) and then the suggested answer.
// To work, there must be *NO* words that match.
ignorableWords.Any(word => sentance.Contains(word)); // Returns True (wrong)
ignorableWords.Any(word => // Returns True (wrong)
sentance.IndexOf(word,
StringComparison.InvariantCultureIgnoreCase) >= 0);
// Only one that returns False
ignorableWords.Any(word =>
Regex.IsMatch(sentance, @$"\b{word}\b", RegexOptions.IgnoreCase));
Summary
.Any(word =>Regex.IsMatch(sentance, @$"\b{word}\b", RegexOptions.IgnoreCase)
- One to many words to check against.
- No internal word failures
- Case is ignored.
精彩评论