Godjenka
Godjenka

Reputation: 47

C# How to only select strings based on a common set of characters?

I have certain numbers placed in lines in a file, the only lines I am interested with are the lines that contain the set of characters "4 2 0" in this order example below:

.....

128 2 2 0 24 49 50 46

129 4 2 0 26 51 36 54 53

130 4 2 0 26 51 41 52 56

....

Here I would discard the line that starts by 128, and keep the two others. What is the best way to do this for the whole file(knowing that lines with such a set of characters are not necessarily at the same spot)? Thank you for your help...

Upvotes: 0

Views: 133

Answers (1)

Gabriel Duarte
Gabriel Duarte

Reputation: 1003

The following should do the trick:

        string str = @"128 2 2 0 24 49 50 46

129 4 2 0 26 51 36 54 53

130 4 2 0 26 51 41 52 56";

        string[] strSplitted = str.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        List<string> result = strSplitted.ToList();

        foreach (var item in strSplitted)
        {
            if (!item.Contains("4 2 0"))
            {
                result.Remove(item);
            }
        }

The "result" variable will have the right results.

Upvotes: 1

Related Questions