c#获得txt文件中字符的个数

本文介绍了一种使用C#读取文本文件的方法,并通过正则表达式统计文件中的数字数量和行数。该代码示例展示了如何使用File.ReadAllText方法读取文件内容,以及如何使用Regex.Matches进行模式匹配。

 try
                {               
                string str = File .ReadAllText ( @"map40x10.txt" );
               // int hz = Regex .Matches ( str , @"[\u4E00-\u9FFF]" ) .Count;//汉字
               // int en = Regex .Matches ( str , "[A-Za-z]" ) .Count;
                int num = Regex .Matches ( str , @"\d" ) .Count;//数字
                int nr = Regex .Matches ( str , @"\r" ) .Count + 1;//行数
                Console .WriteLine ( "数字个数={0},行数={1}" , num , nr );
                Console .WriteLine ( str );
                }
————————————————
版权声明:本文为优快云博主「_lessismore」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/zjc_game_coder/article/details/64921398

### 如何在C#中统计字符串中某个字符出现的次数 在C#中,可以通过遍历字符串并检查每个字符是否与目标字符匹配来统计某个字符字符串中出现的次数。以下是实现这一功能的代码示例: ```csharp public static int CountOccurrences(string input, char targetChar) { if (string.IsNullOrEmpty(input)) { return 0; } int count = 0; foreach (char c in input) { if (c == targetChar) { count++; } } return count; } // 示例用法 string exampleString = "This string consists of a single short sentence."; char targetCharacter = 's'; int result = CountOccurrences(exampleString, targetCharacter); Console.WriteLine($"The character '{targetCharacter}' appears {result} times in the string."); ``` 上述代码定义了一个方法 `CountOccurrences`,它接收一个字符串和一个目标字符作为参数,并返回目标字符字符串中出现的次数[^1]。通过使用 `foreach` 循环逐一检查字符串中的每个字符,可以轻松实现统计功能。 此外,也可以利用 LINQ 提供的功能来简化代码: ```csharp using System.Linq; public static int CountOccurrencesLinq(string input, char targetChar) { if (string.IsNullOrEmpty(input)) { return 0; } return input.Count(c => c == targetChar); } // 示例用法 string exampleString = "This string consists of a single short sentence."; char targetCharacter = 's'; int result = CountOccurrencesLinq(exampleString, targetCharacter); Console.WriteLine($"The character '{targetCharacter}' appears {result} times in the string."); ``` LINQ 的 `Count` 方法允许直接传递一个条件表达式,从而更简洁地实现统计功能[^2]。 ### 注意事项 如果需要忽略大小写进行统计,可以在比较之前将字符串转换为统一的大小写形式(例如全部转为小写或大写)。例如: ```csharp public static int CountOccurrencesIgnoreCase(string input, char targetChar) { if (string.IsNullOrEmpty(input)) { return 0; } string lowerInput = input.ToLower(); char lowerTargetChar = char.ToLower(targetChar); int count = 0; foreach (char c in lowerInput) { if (c == lowerTargetChar) { count++; } } return count; } ``` 此方法确保了统计时不区分大小写[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值