tags:

views:

154

answers:

6

how can I Check if a string contains another string?

A: 
    public bool HasString(string item, List<string> arrayOfStrings)
    {
        return arrayOfStrings.Contains(item);
    }
Bablo
That's not exactly an array, is it? (Though, internally, it is.)
Eric Mickelsen
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
i edited it for clarity..yeah that was a horrible question.
A: 
string lookup = "test";
bool hasString = array.Contains(lookup);
Femaref
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
+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
The assumption is that s2 is the string being passed in?
Joel Etherton
yay for linq! I think this is what the OP was looking for. :-)
townsean
@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
I think the update is what I want but what does it return to figure out if S does contain the substring?
@shorty876 - It returns a boolean value (true/false).
Justin Niessner
A: 
IEnumerable<string> values = new[] { "" };
string searchTarget = "";
string firstMatch = values.FirstOrDefault(s => s.Contains(searchTarget);
if(firstMatch != null)
{
    // ...
}
Merlyn Morgan-Graham
+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
Why use `IndexOf` over `Contains`?
bdukes
I've just wanted to show another approach. Contains is better by the way.
Zafer
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
Why use `IndexOf` over `Contains`?
bdukes