如何在C#中查找文本字符串中以指定字母开头的单词并打印?
找出文本中以字母A开头的单词并输出
这里提供两种符合需求的实现方式,分别用到StartsWith和Substring方法:
方法一:使用StartsWith(推荐,代码更简洁直观)
StartsWith方法可直接判断字符串是否以指定字符开头,还能通过参数控制是否区分大小写:
static void Main(string[] args) { string text = "Anna and Jenny went to America to eat some apples"; string[] words = text.Split(' '); foreach (string word in words) { // 不区分大小写判断是否以A开头,若要严格区分则去掉StringComparison参数 if (word.StartsWith("A", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(word); } } }
方法二:使用Substring
通过Substring截取单词的第一个字符,再和目标字符比较:
static void Main(string[] args) { string text = "Anna and Jenny went to America to eat some apples"; string[] words = text.Split(' '); foreach (string word in words) { // 先判断单词非空,避免索引越界 if (!string.IsNullOrEmpty(word) && (word.Substring(0, 1).Equals("A", StringComparison.OrdinalIgnoreCase))) { Console.WriteLine(word); } } }
补充说明
- 若只需要匹配大写A开头的单词,移除代码中的
StringComparison.OrdinalIgnoreCase参数即可。 - 使用
Substring时必须先判断单词是否为空,防止字符串拆分后出现空值导致索引错误。
内容的提问来源于stack exchange,提问作者Kageus
相关产品推荐
相关产品推荐

