Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何计算c中的某些字符?_C#_Replace_Textbox - Fatal编程技术网

C# 如何计算c中的某些字符?

C# 如何计算c中的某些字符?,c#,replace,textbox,C#,Replace,Textbox,我是C新手,我需要制作一个程序,可以在文本框中计算这些字符。我把replace方法放进去了,但是它说replace方法不重载3个参数。我发现Replace方法不能接受3个参数。问题是我不知道我还能用什么代码。有人能帮忙吗 public Form1() { InitializeComponent(); } private void btn1_Click(object sender, EventArgs e) { lblDolzinaStavka.Text = txtBesedil

我是C新手,我需要制作一个程序,可以在文本框中计算这些字符。我把replace方法放进去了,但是它说replace方法不重载3个参数。我发现Replace方法不能接受3个参数。问题是我不知道我还能用什么代码。有人能帮忙吗

public Form1()
{
    InitializeComponent();
}

private void btn1_Click(object sender, EventArgs e)
{
    lblDolzinaStavka.Text = txtBesedilo.Text.Length.ToString();

    int Sumniki = txtBesedilo.Text.Length - txtBesedilo.Text.Replace("š", "č", "ž").Length;
}
替换用于将字符串中的一个或多个字符替换为另一个。例如,mom.Replaceu,o将返回mom。这并不是计算任何事件的发生率——这根本不是你想要的方法

听起来你想要的是:

// Replace "foo" with a more meaningful name - we don't know what the
// significance of these characters is.
int foo = txtBesedilo.Text.Count(c => c == 'š' || c == 'č' || c == 'ž');
或:

这两个代码段都使用扩展方法,该方法计算集合中有多少项与特定条件匹配。在这种情况下,集合中的项目是txtBesedilo.Text中的字符,条件是它是否是您感兴趣的字符之一。

您可以使用LINQ:

int result = txtBesedilo.Text.Count(x => (x == 'š' || x == 'ž' || x == 'č' ));

那么,您希望替换方法在这里做什么?你不是在寻找替代品,而是在寻找一个计数。我猜他是在试图用void替换字符,并计算与初始字符串的长度差。第二种解决方案不是要在txtBesedilo中对每个字符执行1次搜索,而不是比。计数更有趣吗?@quantdev:是的,它是-这将是相当快的,考虑到阵列有多小。它可能比硬编码版本的效率稍低,但更灵活。您可以在其他地方指定字符集,将其传递到方法或其他任何地方。@JonSkeet非常感谢。
char[] characters = { 'š', 'č', 'ž' };
int foo = txtBesedilo.Text.Count(c => characters.Contains(c));
int result = txtBesedilo.Text.Count(x => (x == 'š' || x == 'ž' || x == 'č' ));