我想计算一个字符串中出现的字符数,然后用这种方式计算:
static void Main(string[] args)
{
string msg;
int count=0;
int counter= 1;
char[] array=new char[10];
Console.WriteLine("Enter any string");
msg = Console.ReadLine();
array = msg.ToCharArray();
Console.WriteLine(array.Length);
for(int i=0; i<array.Length; i++)
{
count = 1;
for (int j = counter; j < array.Length; j++)
{
if (array[i] == array[j])
{
count++;
}
}
counter++;
char[] storing = new char[array.Length];
if (storing.Contains<char>(array[i]))
{
Console.WriteLine("{0} already count", array[i]);
}
else
{
storing[i] = array[i];
Console.WriteLine("{0} Come {1} times",storing[i],count);
}
}
}
但问题是这个存储数组存储了所有字符,我想要当一个字符来检查这个存储数组是否已经有这个字符,如果没有然后存储它,因此我使用Contains方法但它确实&# 39;没有工作。
答案 0 :(得分:1)
dictionary可能是一种更好的数据结构。您的密钥将是您正在阅读的字符,值将是出现次数。
一个简单的例子:
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
static void Main(string[] args)
{
// ... do your normal setup "enter string etc"
Console.WriteLine(array.Length);
Dictionary<char, int> charToOccurencesMappings = str.ToCharArray().GroupBy(s => s).Select(g => new Occurences { Key = g.Key, Count = g.Count() }).ToDictionary(d => d.Key, d => d.Count);
foreach (var mapping in charToOccurencesMappings)
{
Console.WriteLine($"{mapping.Key} occured {mapping.Value} times");
}
}
}
public class Occurences
{
public char Key { get; set; }
public int Count { get; set; }
public Occurences()
{
}
}
LINQ的奇迹。
答案 1 :(得分:0)
您在for循环中声明“存储”数组 ,这意味着每次检查Contains时,您的数组都是空的。考虑将数组的声明移到外部for循环之上。
我还建议将已经检查过的字符存储在HashSet<char>中是比数组更好的选择。
它会将您的代码更改为以下内容:
var storing = new HashSet<char>();
for(int i=0; i<array.Length; i++)
{
if (!storing.Add(array[i]))
continue;
count = 1;
for (int j = counter; j < array.Length; j++
{
if (array[i] == array[j])
{
count++;
}
}
counter++;
}