簡體   English   中英

從文本框中輸入的字符串中讀取所有字符,不重復和每個字符的計數

[英]To read all characters from a string entered in text box without duplicates and count of each character

我想從文本框中輸入的字符串中讀取所有字符而不重復每個字符的計數,然后使用 C#,Asp.Net 將這些值存儲到兩個網格列

例如: My name is Joe

Characters  Occurances
M               2
y               1
n               1
a               1
e               2
i               1
s               1
j               1
o               1
Total           11

然后將這些存儲到網格視圖列

您可以使用 LINQ 運算符 GroupBy:

string str = ":My name is Joe";

var result = str.Where(c => char.IsLetter(c)).
                 GroupBy(c => char.ToLower(c)).
                 Select(gr => new { Character = gr.Key, Count = gr.Count()}).
                 ToList();

這將為您提供包含字段CharacterCount的對象列表。

編輯:我添加了一個Where子句來過濾掉非字母字符。 還增加了不區分大小寫

現在您必須使用result列表作為網格的綁定源。 我對 ASP.NET 綁定過程的理解有點生疏。 您可能需要使用CharacterCount屬性而不是匿名對象創建某些 class 的對象(您不能綁定到字段)

string input = "My name is Joe";

var result = from c in input.ToCharArray()
             where !Char.IsWhiteSpace(c)
             group c by Char.ToLower(c)
             into g
             select new Tuple<string, int>(g.Key.ToString(),g.Count());

int total = result.Select(o => o.Item2).Aggregate((i, j) => i + j);

List<Tuple<string, int>> tuples = result.ToList();

tuples.Add(new Tuple<string, int>("Total", total));

您可以將tuples列表數據綁定到 DataGrid:)

我已經嘗試過簡單的控制台應用程序..希望這會對您有所幫助..您可以在使用 C# 解決算法上查看此內容

在此處輸入圖像描述

結果如下:

在此處輸入圖像描述

如果您不喜歡 LINQ 解決方案,以下是使用 foreach 循環的方法:

string str = ":My name is Joe";

var letterDictionary = new Dictionary<char,int>();

foreach (char c in str) {
    // Filtering non-letter characters
    if (!char.IsLetter(c))
        continue;

    // We use lowercase letter as a comparison key
    // so "M" and "m" are considered the same characters
    char key = char.ToLower(c);

    // Now we try to get the number of times we met
    // this key already.
    // TryGetValue method will only affect charCount variable
    // if there is already a dictionary entry with this key,
    // otherwise its value will be set to default (zero)
    int charCount;
    letterDictionary.TryGetValue(key, out charCount);

    // Either way, we now have to increment the charCount value
    // for our character and put it into dictionary
    letterDictionary[key] = charCount + 1;  
}

foreach (var kvp in letterDictionary) {
    Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
}

最后一個周期的 output 將是:

m: 2
y: 1
n: 1
a: 1
e: 2
i: 1
s: 1
j: 1
o: 1

現在您必須使用其他答案中的一些技術將結果轉換為可以綁定到數據網格的值列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM