我有一个数组,其中包含通过 .ToCharArray
方法从单词转换的字符。我想检查这个数组中发生了多少次字母(单词(。我该怎么做?
一种方式是查找:
Dim letterLookup = yourCharArray.ToLookup(Function(c) c)
' For example the letter e, note that it's case sensitive '
Dim eLetterCount As Int32 = letterLookup("e"c).Count()
这是有效的,并且具有您甚至可以检查String
/Char()
中未包含的字母的优势,结果您将获得0。
顺便说一句,您不需要使用ToCharArray
,可以使用原始字符串使用此代码。
如果您想列出所有包含字母:
Dim allLetters As IEnumerable(Of Char) = letterLookup.Select(Function(kv) kv.key)
如果您想忽略此案,因此将e
和E
视为平等:
Dim letterLookup = yourCharArray.tolookup(Function(c) c, StringComparer.CurrentCultureIgnoreCase)
例如"帐篷"一词。该程序将检查哪封信 发生不止一次(t(并在数组中找到位置(在此 案例0,3(。它还可以在另一个阵列中找到位置 信件。
然后,我也将使用其他方法使用Linq:
Dim duplicateLetterPositions As Dictionary(Of Char,List(Of Integer)) = yourCharArray.
Select(Function(c, index) New With {.Char = c, .Index = index}).
GroupBy(Function(c) c.Char).
Where(Function(grp) grp.Count > 1).
ToDictionary(Function(grp) grp.Key, Function(grp) grp.Select(Function(x) x.Index).ToList())