C# - Checking if strings have this [closed]
how can I Check if a string contains another string?
Why iterate when you can use LINQ? I think you're asking to get all the strings that are substrings of other strings in the array (please correct me if I'm wrong):
var result = strings.Where(s => strings.Any(s2 => s2.Contains(s)));
Update
After your update, the question seems much easier than original. If you just want to find out if a string contains another string, just use the Contains method:
var s = "Hello World!";
var subString = "Hello";
var isContained = s.Contains(subString);
Or if you want to do a case insensitive search, you have to do things a little differently:
var s = "Hello World!";
var subString = "hello";
var isContained = s.IndexOf(subString,
StringComparison.InvariantCultureIgnoreCase) > 0;
You can use the method named IndexOf.
string s1 = "abcd";
string s2 = "cd";
if(s1.IndexOf(s2)>-1) {
// if s2 is found in s1
}
public bool HasString(string item, List<string> arrayOfStrings)
{
return arrayOfStrings.Contains(item);
}
string lookup = "test";
bool hasString = array.Contains(lookup);
IEnumerable<string> values = new[] { "" };
string searchTarget = "";
string firstMatch = values.FirstOrDefault(s => s.Contains(searchTarget);
if(firstMatch != null)
{
// ...
}
The way I'm reading it you're asking if a big string contains another, shorter string?
string bigString = "something";
string testString = "s";
bool containsTestString = bigString.IndexOf(testString) > -1;
精彩评论