用C#语言实现 编程计算每个字符在总的字符串中出现的次数,把不重复的字符及对应的次数全部列取出来

给定字符串:"We can define a computer as a device that accepts input,processes data, stores
data, and produces output. According to themode of processing, computers are either analog or
digital. They can be classified asmainframes, minicomputers, workstations, or microcomputers."编程计算每个字符出现的次数。

第1个回答  2013-03-01
string str = @"We can define a computer as a device that accepts input,processes data, stores
data, and produces output. According to themode of processing, computers are either analog or
digital. They can be classified asmainframes, minicomputers, workstations, or microcomputers.";

char[] carr = str.ToCharArray();
//排序

IEnumerable<char> sortDescendingQuery =
from c in carr
orderby c descending
select c;
//统计

char c1 = '1';
bool first = true;
int c1Count = 0;
foreach (char c2 in sortDescendingQuery)
{
if (first)
{
c1 = c2;
first = false;
}
if (c1 != c2)
{
Console.WriteLine(string.Format("{0} : {1}", c1, c1Count));
c1 = c2;
c1Count = 1;
}
else
{
c1Count++;
}
}

方法2, linq快速搞定:
string str = @"We can define a computer as a device that accepts input,processes data, stores
data, and produces output. According to themode of processing, computers are either analog or
digital. They can be classified asmainframes, minicomputers, workstations, or microcomputers.";

char[] carr = str.ToCharArray();

var q =
from p in carr
group p by p into g
select new
{
g.Key,
NumProducts = g.Count()
};
foreach (var c in q)
{
Console.WriteLine(string.Format("{0}({1}) : {2}", c.Key, (int)c.Key, c.NumProducts));
}本回答被提问者采纳
第2个回答  2013-03-01
/// input 即为输入的字符串
string temp = input.Replace(" ", ""); // 如果不区分大小写就再调用个方法 .ToUpper() /.ToLower();
char tempDelimiter;
while (temp.Length > 0)
{
tempDelimiter = temp[0];
Console.WriteLine("{0}: {1}.", tempDelimiter, temp.Split(tempDelimiter).Length - 1);
temp = temp.Replace(tempDelimiter.ToString(), "");
}
第3个回答  2013-03-01
foreach (char item in sd)
{
int sdas = 0;
for (int i = 0; i < sd.Length; i++)
{
if (item.Equals(sd[i]))
{
sdas++;
}
}
MessageBox.Show(item + "出现了" + sdas + "次");
}本回答被网友采纳
相似回答
大家正在搜