gpt4 book ai didi

c# - 显示字符以及它们出现了多少次?

转载 作者:太空宇宙 更新时间:2023-11-03 19:30:51 26 4
gpt4 key购买 nike

我从用户那里得到一个字符串,然后把它放在一个字符数组中。现在我想显示字符串中的所有字符以及它们出现的次数。我的代码如下 请纠正我?

 using System;
class count
{
public void charcount()
{
int i ;
int count = 0;
string s;
Console.WriteLine("Enter the String:");
s = Console.ReadLine();
char[] carr = s.ToCharArray();
for(i = 0; i < carr.Length; i++)
{
for(int j = 1; j < carr.Length; j++)
{
if(carr[j] == carr[i])
{
count++;
}
else
{
return;
}
Console.WriteLine("The Character " + carr[i] + " appears " + count);
}
}
}

static void Main()
{
count obj = new count();
obj.charcount();
}
}

最佳答案

好吧,由于您没有构建唯一字符列表,您的代码至少会出现问题,您会在原始字符串中找到它们。任何包含多次出现的字符的字符串都会显示奇怪的结果。

这是一个为您计算信息的 LINQ 表达式(您可以在 LINQPad 中运行它以立即查看结果):

void Main()
{
string s = "This is a test, with multiple characters";
var statistics =
from c in s
group c by c into g
select new { g.Key, count = g.Count() };
var mostFrequestFirst =
from entry in statistics
orderby entry.count descending
select entry;
foreach (var entry in mostFrequestFirst)
{
Debug.WriteLine("{0}: {1}", entry.Key, entry.count);
}
}

输出:

 : 6 <-- spacet: 5i: 4s: 4h: 3a: 3e: 3l: 2c: 2r: 2T: 1,: 1w: 1m: 1u: 1p: 1

If you can't use LINQ, here's an example that doesn't use that:

void Main()
{
string s = "This is a test, with multiple characters";
var occurances = new Dictionary<char, int>();
foreach (char c in s)
{
if (occurances.ContainsKey(c))
occurances[c] = occurances[c] + 1;
else
occurances[c] = 1;
}
foreach (var entry in occurances)
{
Debug.WriteLine("{0}: {1}", entry.Key, entry.Value);
}
}

关于c# - 显示字符以及它们出现了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5102870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com