C# 如何仅在字符串的第一句中查找字母的出现次数?

C# 如何仅在字符串的第一句中查找字母的出现次数?,c#,string,char,C#,String,Char,我只想在第一句中找到字母“a”的数字。下面的代码可以在所有句子中找到“a”,但我只想在第一句中找到 static void Main(string[] args) { string text; int k = 0; text = "bla bla bla. something second. maybe last sentence."; foreach (char a in text) { char b = 'a'; if (b

我只想在第一句中找到字母“a”的数字。下面的代码可以在所有句子中找到“a”,但我只想在第一句中找到

static void Main(string[] args)
{
    string text;  int k = 0;
    text = "bla bla bla. something second. maybe last sentence.";

    foreach (char a in text)
    {
        char b = 'a';
        if (b == a)
        {
            k += 1;
        }
    }

    Console.WriteLine("number of a in first sentence is " + k);
    Console.ReadKey();
}
var count = Text.Split(new[] { '.', '!', '?', })[0].Count(c => c == 'a');
您没有定义“句子”,但如果我们假设它总是以句点(
)结尾,只需在循环中添加以下内容:

if (a == '.') {
    break;
}

从此扩展以支持其他句子分隔符。

当遇到“.”(句点)

时,只需“断开”foreach(…)循环,即可将字符串拆分为以“.”分隔的数组,然后计算数组第一个元素(第一个句子)中的“a”字符数


本例假设一个句子由分隔。如果您的字符串中有一个十进制数字(例如123.456),则该数字将被视为分句。将字符串分解成准确的句子是一个相当复杂的练习。

好吧,假设你将一个句子定义为以“.”结尾

使用String.IndexOf()查找第一个“.”的位置。然后,搜索子字符串而不是整个字符串

  • 在文本中查找“.”的位置(可以使用拆分)
  • 从0到“.”实例计算文本中的“a”

  • 这可能比你想要的更详细,但希望它能在你通读的过程中培养理解力

    public static void Main()
        {
            //Make an array of the possible sentence enders. Doing this pattern lets us easily update
            // the code later if it becomes necessary, or allows us easily to move this to an input
            // parameter
            string[] SentenceEnders = new string[] {"$", @"\.", @"\?", @"\!" /* Add Any Others */};
            string WhatToFind = "a"; //What are we looking for? Regular Expressions Will Work Too!!!
            string SentenceToCheck = "This, but not to exclude any others, is a sample."; //First example
            string MultipleSentencesToCheck = @"
            Is this a sentence
            that breaks up
            among multiple lines?
            Yes!
            It also has
            more than one
            sentence.
            "; //Second Example
    
            //This will split the input on all the enders put together(by way of joining them in [] inside a regular
            // expression.
            string[] SplitSentences = Regex.Split(SentenceToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase);
    
            //SplitSentences is an array, with sentences on each index. The first index is the first sentence
            string FirstSentence = SplitSentences[0];
    
            //Now, split that single sentence on our matching pattern for what we should be counting
            string[] SubSplitSentence = Regex.Split(FirstSentence, WhatToFind, RegexOptions.IgnoreCase);
    
            //Now that it's split, it's split a number of times that matches how many matches we found, plus one
            // (The "Left over" is the +1
            int HowMany = SubSplitSentence.Length - 1;
    
            System.Console.WriteLine(string.Format("We found, in the first sentence, {0} '{1}'.", HowMany, WhatToFind));
    
            //Do all this again for the second example. Note that ideally, this would be in a separate function
            // and you wouldn't be writing code twice, but I wanted you to see it without all the comments so you can
            // compare and contrast
    
            SplitSentences = Regex.Split(MultipleSentencesToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            SubSplitSentence = Regex.Split(SplitSentences[0], WhatToFind, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            HowMany = SubSplitSentence.Length - 1;
    
            System.Console.WriteLine(string.Format("We found, in the second sentence, {0} '{1}'.", HowMany, WhatToFind));
        }
    
    以下是输出:

    We found, in the first sentence, 3 'a'.
    We found, in the second sentence, 4 'a'.
    

    请仔细阅读您的代码,直到您能提出一个更具体的问题。您必须首先确定第一句话。隔离那个。那么,找到第一个“a”是微不足道的。不幸的是,准确地识别一个句子可能确实很重要。你如何定义一个句子?一个时期可能发生在各种各样的地方。。。比如1.5或者“她说,”哇。“是的,你需要给句子下定义。小心像“有一天,巴恩斯先生去了商店”这样的句子。“我想了很多,知道这很容易。谢谢,伙计,这很有效。我会包括“!”和“?”作为拆分参数,但除此之外,这是最优雅的方式。回答不错,包括一个输入的文本没有“.”的情况,用于我的upvote。回答不错,比我的短且简单+1给你!!:)对空字符串调用String.Split将返回索引为0的空字符串数组。对与任何拆分字符都不匹配的字符串调用String.Split将返回数组中索引0处的整个字符串。刚刚用“abc”和“A”作为文本进行了测试。是的,这是家庭作业的一部分。我将在另一时间把类似的问题列为家庭作业:)。我是新来的,在编程方面也是。当然希望你的产品代码不是那样写的。你这样做是在浪费硬盘空间。:)浪费硬盘空间?因为几个额外的字符?你应该看看可读代码和较短代码的概念——大多数人都认为可读/可支持的代码要好得多。然而,在不可读代码、可读代码和过多代码之间有一条细线。请记住,为解决同一问题而编写的代码越多,就越有可能出现错误。上面给出的基于LINQ的解决方案(单行)可读性很强,而且简短明了。唯一能让人回想起链接解决方案的方法是,如果你不得不调试它并检查循环,但在这种情况下,这似乎太过分了。对不起,我完全没有听到讽刺的话。=)尽管有更多的bug“潜在线路”,但我也发现总体上bug较少,因为工作更直观,更容易理解。也就是说,我对LINQ示例也没有问题,但是编程新手如果没有这种突破,可能无法真正理解正在发生的事情。
           string SentenceToCheck = "Hi, I can wonder this situation where I can do best";
    
          //Here I am giving several way to find this
            //Using Regular Experession
    
            int HowMany = Regex.Split(SentenceToCheck, "a", RegexOptions.IgnoreCase).Length - 1;
            int i = Regex.Matches(SentenceToCheck, "a").Count;
            // Simple way
    
            int Count = SentenceToCheck.Length - SentenceToCheck.Replace("a", "").Length;
    
            //Linq
    
            var _lamdaCount = SentenceToCheck.ToCharArray().Where(t => t.ToString() != string.Empty)
                .Select(t => t.ToString().ToUpper().Equals("A")).Count();
    
           var _linqAIEnumareable = from _char in SentenceToCheck.ToCharArray()
                                     where !String.IsNullOrEmpty(_char.ToString())
                                     && _char.ToString().ToUpper().Equals("A")
                                     select _char;
    
            int a =linqAIEnumareable.Count;
    
            var _linqCount = from g in SentenceToCheck.ToCharArray()
                             where g.ToString().Equals("a")
                             select g;
            int a = _linqCount.Count();