Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# StringReader Class

I have this problem, I'm using StringReader to find specific words from a textbox, so far is working great, however I need to find a way how to check specific words in every line against a string array.

The following code works:

string txt = txtInput.Text;
string user1 = "adam";
int users = 0;
int systems = 0;

using (StringReader reader = new StringReader(txt))
{
    while ((txt = reader.ReadLine()) != null)
    {
        if (txt.Contains(user1))
        {
            users++;
        }
    }
}

Now, I have created a String Array to store more than one string, but the method Contains seems to only accept a string.

string[] systemsarray = new string[] { "as400", "x500", "mainframe" };

if(txt.Contains(systemsarray))
{
    systems++;
}
// error message: cannot convert from string[] to string

Does anyone have an idea how to do this, or a way to improve it?

Thanks in advance.

like image 303
Hocsan Moya Avatar asked Aug 05 '13 19:08

Hocsan Moya


2 Answers

If you are looking for the existence of any of those words in the line, try:

if(systemsarray.Any(word => txt.Contains(word)))
{
    users++;
}
like image 138
Reed Copsey Avatar answered Sep 20 '22 07:09

Reed Copsey


Why not write yourself an extension method to do this?

public static class StringExtensionMethods
{
    public static bool ContainsAny(this string self, params string[] toFind)
    {
        bool found = false;
        foreach(var criteria in toFind)
            {
                if (self.Contains(criteria))
                {
                    found = true;
                    break;
                }
            };

        return found;
    }   // eo ContainsAny    
}

Usage:

string[] systemsarray = new string[] { "as400", "x500", "mainframe" };

if(txt.ContainsAny(systemsarray))
{
    systems++;
}
// error message: cannot convert from string[] to string
like image 31
Moo-Juice Avatar answered Sep 22 '22 07:09

Moo-Juice