前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# 计算某个字符在字符串中出现的次数

C# 计算某个字符在字符串中出现的次数

作者头像
用户4324355
发布2022-07-23 07:43:22
4.4K0
发布2022-07-23 07:43:22
举报
文章被收录于专栏:C#笔记C#笔记

C# 计算某个字符在字符串中出现的次数,可以应用于计算关键词密度,判断URL目录的层级深度。

1. 使用可枚举 Enumerable.Count() 方法,引用空间 (System.Linq)

推荐的解决方案是使用System.Linq的Count()方法来计算字符串中给定字符的出现次数。该方法如下所示:

代码语言:javascript
复制
using System;
using System.Linq;
 
public class Example
{
    public static void Main()
    {
        string str = "Techie Delight";
        char ch = 'e';
 
        int freq = str.Count(f => (f == ch));
        Console.WriteLine(freq);
    }
}
 
/*
    Output: 3
*/

2. 使用可枚举 Enumerable.Where() 方法,引用空间 (System.Linq)

下面是另一个LINQ解决方案,它使用Where()方法过滤字符串。下面的代码示例显示了如何使用此选项:

代码语言:javascript
复制
using System;
using System.Linq;
 
public class Example
{
    public static void Main()
    {
        string str = "Techie Delight";
        char ch = 'e';
 
        int freq = str.Where(x => (x == ch)).Count();
        Console.WriteLine(freq);
    }
}
 
/*
    Output: 3
*/

3. 使用字符串的 String.Split() 方法

这是使用指定的字符将字符串拆分为数组的String.Split()方法,通过字符串数组的Length属性来确定计数。这个方法示例如下所示:

代码语言:javascript
复制
using System;
 
public class Example
{
    public static void Main()
    {
        string str = "Techie Delight";
        char ch = 'e';
 
        int freq = str.Split(ch).Length - 1;
        Console.WriteLine(freq);
    }
}
 
/*
    Output: 3
*/

4. 使用 foreach 循环

我们也可以为这个简单的任务编写自己的逻辑。其思想是使用foreach循环对字符串中的字符进行迭代,并保持匹配的字符计数。

代码语言:javascript
复制
using System;
 
public class Example
{
    public static void Main()
    {
        string str = "Techie Delight";
        char ch = 'e';
 
        int freq = 0;
        foreach (char c in str)
        {
            if (c == ch) {
                freq++;
            }
        }
 
        Console.WriteLine(freq);
    }
}
 
/*
    Output: 3
*/

5. 使用 Regex.Matches() 方法

正则表达式Regex.Matches()方法用于搜索指定正则表达式的所有匹配项的指定输入字符串。我们可以使用它来计算字符串中字符的出现次数。

代码语言:javascript
复制
using System;
using System.Text.RegularExpressions;
 
public class Example
{
    public static void Main()
    {
        string str = "Techie Delight";
        char ch = 'e';
 
        int freq = Regex.Matches(str, ch.ToString()).Count;
        Console.WriteLine(freq);
    }
}
 
/*
    Output: 3
*/

原文链接

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 使用可枚举 Enumerable.Count() 方法,引用空间 (System.Linq)
  • 2. 使用可枚举 Enumerable.Where() 方法,引用空间 (System.Linq)
  • 3. 使用字符串的 String.Split() 方法
  • 4. 使用 foreach 循环
  • 5. 使用 Regex.Matches() 方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档