using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private Dictionary<string, int> dict = new Dictionary<string, int>();
private List<CountResult> results = new List<CountResult>();
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strTest = "ii'=yes!23455!a@s#yes$fr%yes&gh123gg_tyuiooo's_g--uii(";
var spl = strTest.Split(" !\"#$%&()-=^~\\|@`[{;+:*]},<.>/?_".ToCharArray());
foreach (var s in spl)
{
var t = s;
if (!string.IsNullOrWhiteSpace(t))
{
// 空白以外
if (t.EndsWith("'"))
{
t = t.Substring(0, t.Length - 1);
}
if (t.Length >= 2)
{
// 2文字以上
// 数字のみ判定
var allnum = true;
foreach (var c in t)
{
if ("0123456789".IndexOf(c) < 0)
{
allnum = false;
break;
}
}
if (!allnum)
{
// 数字のみ以外
var lower = t.ToLower();
if (this.dict.ContainsKey(lower))
{
this.dict[lower]++;
}
else
{
// 辞書に無い
this.dict.Add(lower, 1);
}
}
}
}
}
foreach (var a in this.dict)
{
this.results.Add(new CountResult(a.Key, a.Value));
}
this.results.Sort((num1, num2) =>
{
if (num2.Count == num1.Count)
{
return num1.Word.CompareTo(num2.Word);
}
else
{
return num2.Count - num1.Count;
}
});
foreach (var cr in this.results)
{
this.listBox1.Items.Add(cr.Word + "----------" + cr.Count.ToString());
}
}
/// <summary>
///结果排序类
/// </summary>
private class CountResult
{
public CountResult(string word, int count)
{
this.Word = word;
this.Count = count;
}
public string Word
{
get;
private set;
}
public int Count
{
get;
private set;
}
}
}
}
-----------------------------------------------------------------------
var text = @"C# (pronounced C sharp) is a programming language thatis designed for building a variety of applications thatrun on the .NET Framework. C# is simple, powerful,type-safe, and object-oriented. The many innovationsin C# enable rapid application development whileretaining the expressiveness and elegance of C-stylelanguages. ";
var splitter = new Regex(@"[\s\(\)\.,\n\r]+", RegexOptions.Multiline);
var wordCount = from word in splitter.Split(text)
where !string.IsNullOrEmpty(word)
group word by word
into g
orderby g.Count()
select new { Count = g.Count(), Word = g.Key };
foreach (var item in wordCount)
{ Console.WriteLine(item);}