简体   繁体   English

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

[英]How to find the number of occurrences of a letter in only the first sentence of a string?

I want to find number of letter "a" in only first sentence. 我只想在第一句话中找到字母“ a”的数量。 The code below finds "a" in all sentences, but I want in only first sentence. 下面的代码在所有句子中都找到“ 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();
}

This will split the string into an array seperated by '.', then counts the number of 'a' char's in the first element of the array (the first sentence). 这会将字符串拆分成一个以“。”分隔的数组,然后计算该数组的第一个元素(第一个句子)中“ a”字符的数量。

var count = Text.Split(new[] { '.', '!', '?', })[0].Count(c => c == 'a');

This example assumes a sentence is separated by a . 本示例假定一个句子用分隔 , ? or ! . If you have a decimal number in your string (eg 123.456), that will count as a sentence break. 如果您的字符串中有一个十进制数字(例如123.456),则将其视为句子中断。 Breaking up a string into accurate sentences is a fairly complex exercise. 将字符串分成准确的句子是一项相当复杂的练习。

You didn't define "sentence", but if we assume it's always terminated by a period ( . ), just add this inside the loop: 您没有定义“句子”,但是如果我们假设它总是以句点( . )终止,只需在循环内添加它:

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

Expand from this to support other sentence delimiters. 从此扩展以支持其他句子定界符。

This is perhaps more verbose than what you were looking for, but hopefully it'll breed understanding as you read through it. 这也许比您要查找的内容更为冗长,但希望它能帮助您在阅读过程中加深理解。

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));
    }

Here is the output: 这是输出:

We found, in the first sentence, 3 'a'.
We found, in the second sentence, 4 'a'.
       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();

Simply "break" the foreach(...) loop when you encounter a "." 遇到“。”时,只需“破坏” foreach(...)循环。 (period) (期)

Well, assuming you define a sentence as being ended with a '.'' 好吧,假设您将句子定义为以'。

Use String.IndexOf() to find the position of the first '.'. 使用String.IndexOf()查找第一个“。”的位置。 After that, searchin a SubString instead of the entire string. 之后,搜索一个SubString而不是整个字符串。

  1. find the place of the '.' 找到“。”的位置 in the text ( you can use split ) 在文本中(可以使用split)
  2. count the 'a' in the text from the place 0 to instance of the '.' 计算文本中从位置0到实例'a'的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM