目標是輸入任意英文文章後,可計算出各字母出現了幾次。
下面是我用For迴圈的做法,想請問改成用Lambda的話可以精簡到怎樣?
//前置作業開始
//txt為隨意輸入的英文文章
string txt = "Property is used to gets or sets the element at the specified index. Properties of List: It is different from the arrays. ";
//過濾用
string[] words = txt.Split(' ',',','.','!','?',':');
List<string> cleanTxt = new List<string>();
//全轉為小寫
foreach (string word in words)
{
if (word != "") {
cleanTxt.Add(word.ToLower());
}
}
System.Console.WriteLine("---------");
//前置作業結束
//分別儲存英文單字與出現次數
List<string> targetWord = new List<string>();
int[] targetWordnum = new int[cleanTxt.Count];
//進迴圈判斷
for (int i = 0, j = 0; i < cleanTxt.Count; i++) {
if (!targetWord.Contains(cleanTxt[i])) {
targetWord.Add(cleanTxt[i]);
targetWordnum[j] = 1;
j += 1;
} else {
int k = targetWord.IndexOf(cleanTxt[i]);
targetWordnum[k] += 1;
//System.Console.WriteLine($"{cleanTxt[i]}:{targetWordnum[k]}");
}
}
//畫面輸出結果
System.Console.WriteLine("---------");
for (int i = 0; i < targetWord.Count; i++) {
System.Console.WriteLine($"{targetWord[i]}:{targetWordnum[i]}");
}
Spilt
完後可以使用where
,select
,String.Join
組成一個字串.
在用GroupBy
來做分群
string txt = "Property is used to gets or sets the element at the specified index. Properties of List: It is different from the arrays. ";
var words = txt.Split(' ',',','.','!','?',':')
.Where(s=>!string.IsNullOrEmpty(s))
.Select(x=>x.ToLower());
var wordLine = string.Join("", words);
var result = wordLine.GroupBy(x => x).Select(x => new {word = x.Key, Count = x.Count()});
foreach (var item in result)
{
Console.WriteLine($"{item.word}:{item.Count}");
}
您可能要先解決資料結構
的問題,再來考慮怎麼改成用Lambda Function來做,像這種很明顯有Key/Value Pair
的型態,基本上就可以直接用Dictionary來做,改完就會發現根本沒有改寫Lambda的必要~XDDD
e.g.
string txt = "Property is used to gets or sets the element at the specified index. Properties of List: It is different from the arrays. ";
char[] splitChar = { ' ', ',', '.', '!', '?', ':' };
string[] words = txt.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, int> wordsDict = new Dictionary<string, int>();
for (int i = 0; i < words.Length; i++)
{
string word = words[i].ToLower();
if (!wordsDict.ContainsKey(word))
{
wordsDict.Add(word, 1);
}
else
{
wordsDict[word] += 1;
}
}
var dictEnum = wordsDict.AsEnumerable(); // Enum化,方便列舉輸出
foreach (var item in dictEnum)
{
// 輸出
Console.WriteLine($"{item.Key}:{item.Value}");
}
Console.ReadKey();