The maximum number of occurrences of a character appears in an array of strings

In C #, given an array:

string[] myStrings = new string[] {
  "test#test",
  "##test",
  "######", // Winner (outputs 6)
};

How can I find the maximum number of occurrences that a character #appears on one line?

My current solution:

int maxOccurrences = 0;
foreach (var myString in myStrings)
{
    var occurrences = myString.Count(x => x == '#');
    if (occurrences > maxOccurrences)
    {
        maxOccurrences = occurrences;
    }
}

return maxOccurrences;

Is they a simpler way with linq that can act directly in an array myStrings[]?

And can this be done in an extension method that can work on anyone IEnumerable<string>?

+4
source share
3 answers

First of all, run your lines in sequence with the number of matches:

myStrings.Select(x => x.Count(x => x == '#')) // {1, 2, 6} in your example

Then select the maximum value:

int maximum = myStrings
    .Select(s => s.Count(x => x == '#'))
    .Max(); // 6 in your example

Make an extension method:

public static int CountMaximumOccurrencesOf(this IEnumerable<string> strings, char ch)
{
    return strings
        .Select(s => s.Count(c => c == ch))
        .Max();
}

HOWEVER. # char , . , : Unicode ?, . "Unicode aware", ( , , ):

private static IEnumerable<string> EnumerateCharacters(string s)
{
    var enumerator = StringInfo.GetTextElementEnumerator(s.Normalize());
    while (enumerator.MoveNext())
        yield return (string)enumerator.Value;
}

:

public static int CountMaximumOccurrencesOf(this IEnumerable<string> strings, string character)
{
    return strings
        .Select(s => s.EnumerateCharacters().Count(c => String.Equals(c, character, StringComparison.CurrentCulture))
        .Max();
}

, Max() , ( DefaultIfEmpty(), ). , ( , 0), :

public static int CountOccurrencesOf(this IEnumerable<string> strings,
    string character,
    StringComparison comparison = StringComparison.CurrentCulture)
{
    Debug.Assert(character.EnumerateCharacters().Count() == 1);

    return strings
        .Select(s => s.EnumerateCharacters().Count(c => String.Equals(c, character, comparison ));
}

:

var maximum = myStrings.CountOccurrencesOf("#").Max();

:

var maximum = myStrings.CountOccurrencesOf("Γ ", StringComparison.CurrentCultureIgnoreCase)
    .Max();

, , (en-US), , , StringComparison.InvariantCulture. , String.Normalize() .

+8

- . DefaultIfEmpty, , myStrings , 0.

var maximum = myStrings.Select(e => e.Count(ee => ee == '#')).DefaultIfEmpty().Max();
+1

You can do this using Linqin combination with Regex:

myStrings.Select(x => Regex.Matches(x, "#").Count).max();
0
source

Source: https://habr.com/ru/post/1626554/


All Articles