我必须计算一个特定角色的出现次数.我能做些什么? [英] I have to count the number of occurances of a particular character. What can i do?

查看:60
本文介绍了我必须计算一个特定角色的出现次数.我能做些什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须计算一个特定角色的出现次数.我该怎么办?

I have to count the number of occurances of a particular character. What can i do?

推荐答案

您没有提供任何详细信息,因此答案只能是一样的模糊.

如果您想对字符进行计数,请遍历字符串并对其进行计数.
You have not given any details so the answers can only be just as vague.

If you want to count characters then iterate through the string and count them.


在此处尝试以下小示例:

Try this small sample here:

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);
            }
        }
    }
}



干杯!

—MRB



Cheers!

—MRB


一种快速而肮脏的黑客使用Split方法,例如:
A quick and dirty hack uses the Split method, for instance:
char [ ] sep = {'i'};
string s = "how many 'i's are in this string?";
int count =  s.Split(sep).Length - 1;


这篇关于我必须计算一个特定角色的出现次数.我能做些什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆