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

您所在的位置:网站首页 一串字符串求出现字母的次数 C# 计算某个字符在字符串中出现的次数

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

2024-07-11 20:45| 来源: 网络整理| 查看: 265

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 */

原文链接



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3