此函数计算字母在给定字符串中出现的频率并将其放入数组中(索引是ascii-number of letter和value ist count occurrence)。现在我需要返回字母(它已经做过)和值。只是通过在线阅读我无法弄清楚如何使用ref和替代品来做到这一点。
static char MostCommonLetter(string s)
{
int[] occurrances = new int[255];
for (int i = 0; i < s.Length; i++)
{
if (char.IsLetter(s[i]))
{
int ascii = (int)s[i];
occurrances[ascii]++;
}
}
char maxValue = (char)Array.IndexOf(occurrances, occurrances.Max());
return maxValue;
}
答案 0 :(得分:4)
在C#7及以上版本中,Value Tuples是您最好的选择。您可以按如下方式定义函数:
static (char letter, int occurrences) MostCommonLetter(string s)
{
int[] occurrences = new int[255];
for (int i = 0; i < s.Length; i++)
{
if (char.IsLetter(s[i]))
{
int ascii = (int)s[i];
occurrances[ascii]++;
}
}
char letter = (char)Array.IndexOf(occurrences, occurrences.Max());
return (index: letter, occurrences: occurrences);
}
然后您可以像这样引用输出:
var (index, occurrences) = MostCommonLetter(yourString);
答案 1 :(得分:0)
您可以使用“out”参数从函数中返回其他参数。
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
答案 2 :(得分:0)
另一种解决方案是使用LINQ:
string str = "Hello World!";
var result = str.GroupBy(c => c)
.Select(group => new { Letter = group.Key, Count = group.Count() })
.OrderByDescending(x => x.Count)
.First();
char letter = result.Letter;
int count = result.Count;
letter =&#39; l&#39;
count = 3
答案 3 :(得分:0)
在C#中执行所需操作的最佳和最灵活的方法是使用结构。
以这种方式定义结构并使用它同时返回多个结果(结构甚至可以包含函数......您可以将这些结构看作更亮的类):
namespace YourApp.AnyNamespace {
// Other things
public struct SampleName
{
public char mostCommon;
public int occurancies;
}
}