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

时间:2011-11-10 21:54:24

标签: 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)
        {
            k += 1;
        }
    }

    Console.WriteLine("number of a in first sentence is " + k);
    Console.ReadKey();
}

7 个答案:

答案 0 :(得分:9)

这会将字符串拆分为由'。'分隔的数组,然后计算数组第一个元素(第一个句子)中'a'字符的数量。

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

此示例假定句子由分隔。如果你的字符串中有一个十进制数字(例如123.456),那将被视为句子中断。将字符串分解为准确的句子是一项相当复杂的练习。

答案 1 :(得分:1)

你没有定义“句子”,但如果我们假设它总是以句点(.)结束,只需在循环内添加:

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

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

答案 2 :(得分:1)

这可能比你想要的更冗长,但希望它会在你阅读时产生理解。

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'.

答案 3 :(得分:0)

遇到“。”时,只需“中断”foreach(...)循环即可。 (周期)

答案 4 :(得分:0)

好吧,假设您将一个句子定义为以'。''

结尾

使用String.IndexOf()查找第一个'。'的位置。之后,搜索SubString而不是整个字符串。

答案 5 :(得分:0)

  1. 找到'。'的位置在文中(你可以使用拆分)
  2. 计算文本中的'a',从地点0到'。'的实例。

答案 6 :(得分:0)

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