Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.RegularExpressions;
- class ExtractSentencesContainingCertainWord
- {
- //Write a program that extracts from a given text all sentences containing given word.
- //Example: The word is "in". The text is:
- //We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
- //The expected result is:
- //We are living in a yellow submarine.
- //We will move out of it in 5 days.
- //Consider that the sentences are separated by "." and the words – by non-letter symbols.
- static List<int> FindSentencesWithWord(string[] sentences, string word)//Returns a list with the indices of the sentences that contain the searched word
- {
- List<int> sentencesToOutput = new List<int>();
- for (int i = 0; i < sentences.Length; i++)
- {
- if (Regex.Matches(sentences[i], "\\b" + word + "\\b",RegexOptions.IgnoreCase).Count > 0)
- {
- sentencesToOutput.Add(i);
- }
- }
- return sentencesToOutput;
- }
- static void Main()
- {
- string text = "We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
- string word = "in";
- List<int> indecesOfwordInText = new List<int>();
- string[] sentencesArray;
- sentencesArray = text.Split('.');
- indecesOfwordInText = FindSentencesWithWord(sentencesArray, word);//Get the sentences that contain the word
- //Print on the console the found sentences
- for (int i = 0; i < indecesOfwordInText.Count; i++)
- {
- Console.WriteLine((sentencesArray[(indecesOfwordInText[i])] + ".").Trim()); //Add the dot and trim the emty spaces of each sentence that we are printing
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement