You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 15:25:23