Как найти количество вхождений буквы только в первом предложении строки? - PullRequest
0 голосов
/ 11 ноября 2011

Я хочу найти номер буквы «а» только в первом предложении. Код ниже находит «а» во всех предложениях, но я хочу только в первом предложении.

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 ]

9 голосов
/ 11 ноября 2011

Это разделит строку на массив, разделенный символом «.», А затем подсчитает количество символов «a» в первом элементе массива (первое предложение).Предполагается, что предложение разделено . , ? или ! .Если в вашей строке есть десятичное число (например, 123.456), это будет считаться разрывом предложения.Разбить строку на точные предложения - довольно сложное упражнение.

1 голос
/ 11 ноября 2011

Возможно, это более многословно, чем то, что вы искали, но, надеюсь, оно будет порождать понимание, когда вы будете его читать.

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'.
1 голос
/ 11 ноября 2011

Вы не определили «предложение», но если мы предполагаем, что оно всегда заканчивается точкой (.), просто добавьте это внутри цикла:

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

Расширить это, чтобы поддержать другие разделители предложений.

0 голосов
/ 08 ноября 2012
       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();
0 голосов
/ 11 ноября 2011
  1. найти место '.' в тексте (можно использовать сплит)
  2. посчитайте 'a' в тексте с места 0 до экземпляра '.'
0 голосов
/ 11 ноября 2011

Ну, при условии, что вы определили предложение как заканчивающееся '.' '

Используйте String.IndexOf (), чтобы найти позицию первого '.'. После этого ищите в подстроке вместо всей строки.

0 голосов
/ 11 ноября 2011

Просто "разорвите" цикл foreach(...), когда вы встретите "."(Период)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...