所以我有这个问题。

编写一个程序,从文本中提取包含特定单词的所有句子。
我们接受句子之间用字符“。”分隔。单词之间用一个不是字母的字符隔开。

示例文本:

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.

样本结果:

We are living in a yellow submarine.

We will move out of it in 5 days.


到目前为止,这是我的代码。

public static string Extract(string str, string keyword)
    {

        string[] arr = str.Split('.');
        string answer = string.Empty;

        foreach(string sentence in arr)
        {
            var iter = sentence.GetEnumerator();
            while(iter.MoveNext())
            {
                if(iter.Current.ToString() == keyword)
                    answer += sentence;
            }
        }

        return answer;
    }


好吧,它不起作用。我用以下代码称呼它:

string example = "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 keyword = "in";
string answer = Extract(example, keyword);
Console.WriteLine(answer);


它不输出任何东西。因为我不熟悉迭代器,所以可能是迭代器的一部分。

无论如何,问题提示表明我们应该使用splitIndexOf方法。

最佳答案

尝试:

public static string Extract(string str, string keyword)
{
    string[] arr = str.Split('.');
    string answer = string.Empty;

    foreach(string sentence in arr)
    {
        //Add any other required punctuation characters for splitting words in the sentence
        string[] words = sentence.Split(new char[] { ' ', ',' });
        if(words.Contains(keyword)
        {
            answer += sentence;
        }
    }

    return answer;
}

10-08 03:05