C#如何计算我用此字符串写的字母数 [英] C# how to count number of letters which I wrote with this string

查看:178
本文介绍了C#如何计算我用此字符串写的字母数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态类MyExtension,它具有CountOf静态函数,该函数必须返回我写在字符串中的那个字母的数字.在Main中,我必须这样写`

I have a static class MyExtension,which has CountOf static function,this function must return number of that letters,which i wrote in string.In Main i must write like this`

string str = "hello";
     int r = str.CountOf(''l'');
     Console.WriteLine(r);


它将打印2,因为字符串中有两个"l"字母.

我尝试过的事情:

我已经尝试过这样的事情


It will print 2, because there are two ''l'' letter in string.

What I have tried:

i have tried like this`

static public int CountOf(this string str,char ch)
        {

            return str.Count();
        }


但我知道它是错误的,因为它的返回字符串为


but i know it''s false,because it''s return number of string

推荐答案

有很多方法可以做到这一点,但是最简单的方法就是蛮力.
但是...这是您的作业,所以我不会给您任何代码!

1)创建一个名为count的本地interegr变量,并将其设置为零.
2)在字符串上使用foreach循环访问每个字符
2.1)在循环中,检查当前字符是否与搜索"字符匹配
2.1.1)如果匹配,请递增count
3)循环后,返回count
There are a lot of ways to do this, but the simplest is just to brute force it.
But ... this is your homework, so I''ll give you no code!

1) Create a local interegr variable called count and set it to zero.
2) Use a foreach loop on the string to access each character
2.1) Inside the loop, check if the current character matches the "search for" character
2.1.1) If it matches, increment count
3) After the loop, return count


您必须遍历char的集合,将它们进行比较以输入并返回字符串中搜索到的字母的计数.

You have to go through the collection of chars, compare them to input and return the count of searched letter in a string.

string str = "hello";
char input = 'l';
int counter = 0;
//method 1
foreach(char a in str)
{
	if(a==input) counter++; 
}
//counter = 2

//method 2 - linq
var result = str.Count(x=>x==input);
//result = 2


您可以使用 LINQ 计数,请在此处查看答案: count字符串中的字符数 [ ^ ]
You could use LINQ count, see answers here: count the number of characters in a string[^]


这篇关于C#如何计算我用此字符串写的字母数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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