how can I Check if a string contains another string?
A:
public bool HasString(string item, List<string> arrayOfStrings)
{
return arrayOfStrings.Contains(item);
}
Bablo
2010-09-03 16:03:23
That's not exactly an array, is it? (Though, internally, it is.)
Eric Mickelsen
2010-09-03 16:05:14
I don't think this is what the OP is looking for. This will return if the array contains the item. I think he's looking for something that returns if the item contains anything in the array.
Joel Etherton
2010-09-03 16:05:46
i edited it for clarity..yeah that was a horrible question.
2010-09-03 16:09:01
I think this is backwards. This will return the items in the array where the string and the array string are exact. OP's request appears to request if the string contains the array item. (though I could be wrong, the question isn't terribly clear)
Joel Etherton
2010-09-03 16:07:35
+6
A:
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;
Justin Niessner
2010-09-03 16:04:21
@Joel - No. The assumption was that there was a single string array. For each element in the array, the OP wanted to find out if it was a substring of any other string in the same array.
Justin Niessner
2010-09-03 16:11:59
A:
IEnumerable<string> values = new[] { "" };
string searchTarget = "";
string firstMatch = values.FirstOrDefault(s => s.Contains(searchTarget);
if(firstMatch != null)
{
// ...
}
Merlyn Morgan-Graham
2010-09-03 16:07:58
+2
A:
You can use the method named IndexOf.
string s1 = "abcd";
string s2 = "cd";
if(s1.IndexOf(s2)>-1) {
// if s2 is found in s1
}
Zafer
2010-09-03 16:10:19
A:
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;
Steve Danner
2010-09-03 16:10:21