本文介绍了我必须计算一个特定角色的出现次数.我能做些什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须计算一个特定角色的出现次数.我该怎么办?
I have to count the number of occurances of a particular character. What can i do?
推荐答案
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace CountCharacters
{
static class Program
{
static void Main()
{
Dictionary<Char, int> countChars = new Dictionary<Char,int>();
String test = "Hello man how''s it going. Some characters here in this string. Some stuff to test our character counter with.";
foreach (Char ch in test)
{
if(countChars.ContainsKey(ch))
{
countChars[ch]++;
}
else
{
countChars.Add(ch, 1);
}
}
List<CharInt> list = new List<CharInt>();
foreach (Char key in countChars.Keys)
{
list.Add(new CharInt(key, countChars[key]));
}
list.Sort();
foreach (CharInt ci in list)
{
Console.WriteLine("{0} : {1}", ci.Char, ci.Int);
}
Console.ReadLine();
}
private class CharInt : IComparable<CharInt>
{
public Char Char;
public int Int;
public CharInt(Char c, int i)
{
this.Char = c;
this.Int = i;
}
public int CompareTo(CharInt other)
{
if (other == null) return 1;
return -1 * this.Int.CompareTo(other.Int);
}
}
}
}
干杯!
Cheers!
char [ ] sep = {'i'};
string s = "how many 'i's are in this string?";
int count = s.Split(sep).Length - 1;
这篇关于我必须计算一个特定角色的出现次数.我能做些什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!