Mykhalik
Mykhalik

Reputation: 244

Find in text with Linq

So I have such construction for searching words in text

 FileStream fs = new FileStream(fileName, FileMode.Open);
 StreamReader sr = new StreamReader(fs);
 fullText = sr.ReadToEnd();
 string[] arr = fullTetx.Split(' ');
 for (int i = 0; i < arr.Length; i++)//
 {
       if (arr[i].Trim() == "LOAD")
           Console.WriteLine(arr[i].Trim());
 }
 sr.Close();
 fs.Close();

I must get all similar words ignore case with Linq.

For example:

LOAD(PLOT) = SET 4 = THRU 16,34 THRU 37, 48 THRU 53,61 FORCE(PLOT,CORNER)ds STRESS(PLOT,CORNER) mama dad SPC = 1 LOAD = 1 Load , load.

and I must get:

LOAD LOAD Load load

Upvotes: 0

Views: 269

Answers (4)

Phil
Phil

Reputation: 42991

Or how about:

// If you want the lines that contain "LOAD"
var loads = File.ReadLines(fileName).
            SelectMany (l => l.Split(' ')).
            Where (s => s.ToUpperInvariant().Contains("LOAD"));

foreach(var s in loads)
{
    Console.WriteLine(s);
}

// If you just want instances of "LOAD"
var loads = File.ReadLines(fileName).
            SelectMany (l => l.Split(' ')).
            Where (s => s.ToUpperInvariant() == "LOAD");

foreach(var s in loads)
{
    Console.WriteLine(s);
}

Upvotes: 0

Killo
Killo

Reputation: 300

var matches = Regex.Matches(fullTetx, @"load", RegexOptions.IgnoreCase);

Upvotes: 2

Stecya
Stecya

Reputation: 23266

Try this one

    var result = arr.Where(x => string.Equals(x, "LOAD",StringComparison.OrdinalIgnoreCase)).ToList();

Upvotes: 2

Kek
Kek

Reputation: 3195

I am not sure I understood where LOAD is taken from. Is it hardecoded ? if yes then something like :

foreach(var word in arr.Where(w => w.ToUpper() == "LOAD"))
    Console.WriteLine(word);

Upvotes: 4

Related Questions