检查字符串是否以特定顺序包含单词

4

有一个有趣的问题,假设你有一个包含三个句子的列表:

Bill cat had

Bill had a cat

Cat had Bill

如何使用.Contains() 或其他方法来检查列表中的句子是否以特定顺序包含单词,算法如下:

1)通过 foreach 循环运行句子列表

2)检查句子是否按此顺序包含单词 => Bill + had + cat

3)返回该句子

因此,除了按顺序排列单词的句子外,其他所有句子都将返回 false。有关实现此操作的想法吗? :)


你可以使用正则表达式从列表中查找匹配的字符串。 - jadavparesh06
“order of words” 条件可以满足吗?@jadavparesh06 - PewK
可以使用正则表达式指定该条件。 - jadavparesh06
在上面的循环中,我们只需要为“Bill had a Hat”返回true吗?对于其他语句,我们需要返回false。这是你的问题吗? - sarathkumar
是的先生,就是这样!@sarathkumar - PewK
4个回答

2
List<string> ss = new List<string>();
ss.Add("Bill had cat");
string inputstring = "In 2012, Bill had a cat";
foreach (string s in ss)
{
    string[] split = s.Split(' ');
    string regex = ".*";
    for(int a = 0; a<split.Length;a++)
        regex += split[a]+".*";
    Match temp = Regex.Match(inputstring, regex);
    if (temp.Success)
    {
        MessageBox.Show("String \"" + inputstring  + "\" matches");
    }
}

请尝试是否可行,这是区分大小写的,请注意


嗯,它实际上对于“Bill cat had”返回true。我该如何更改它,我有点不理解那段代码背后的逻辑,先生。 - PewK
你的输入字符串是什么? - Vajura
由于我需要它根据问题中提到的条件返回true,所以我的输入字符串是“在2012年,比尔有一只猫”。但它返回false。 - PewK
但是对于那个字符串,“Bill cat had”会是错误的,对吧?我的意思是猫出现在had之后。“Bill had a cat”这个字符串是正确的,因为它是按照顺序排列的。 - Vajura
是的,如果它们依次包含“Bill + had + Cat”这几个单词,那么它应该为true。就像这样:Bill > had > Cat。抱歉一再纠缠 :) - PewK
修改了我的答案,请现在尝试。如果您想要不同的匹配,请将 ss.Add("Bill cat had"); 中的 "Bill cat had" 更改为另一个字符串,然后按照该顺序进行匹配。 - Vajura

2

尝试以下解决方案,它有效。

class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Add("Bill cat had");
            list.Add("Bill had a cat");
            list.Add("Bill had cat");
            list.Add("Cat had Bill");
            Regex rex = new Regex(@"((Bill)).*((had)).*((cat))");

            foreach (string str in list)
            {
                if (rex.IsMatch(str))
                {
                    Console.WriteLine(str);
                }
            }
            Console.ReadLine();
        }
    }

它在我的控制台应用程序上正常工作,不知道为什么它对你抛出了异常。 - jadavparesh06

1
这对我有效。
class Program
{
    static List<string> sentences = new List<string>();
    static List<string> pattern = new List<string>();
    static List<string> results = new List<string>();

    static void Main(string[] args)
    {
        //sentences are in order
        sentences.Add("Bill cat had");
        sentences.Add("Bill had a cat");
        sentences.Add("Cat had Bill");
        sentences.Add("Bill had cats");

        //patters are in order
        pattern.Add("Bill");
        pattern.Add("had");
        pattern.Add("cat");

        // call the searchString method
        results = searchString(sentences, pattern);

        foreach (string res in results)
        {
            Console.WriteLine(res);
        }

        Console.Read(); // just keep program running when debugged
    }

    static List<string> searchString(List<string> sentences, List<string> patterns)
    {
        bool result = false;
        List<string> resultLIst = new List<string>();

        foreach (string sen in sentences)
        {
            int j = 0;
            foreach (string pat in pattern)
            {
                if (sen.Contains(pat))
                {
                    if (j <= sen.IndexOf(pat))
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                        break;
                    }
                    j = sen.IndexOf(pat);
                }
                else
                {
                    result = false;
                    break;
                }
            }

            if (result)
                resultLIst.Add(sen); // get the matching sentence
        }

        return resultLIst; // return matchin sentences
    }

}

1

也请检查这个答案

 protected void Page_Load(object sender, EventArgs e)
        {
            string message = "";
            string[] list = new string[] { "Bill cat had", "Bill had a cat", "Cat had Bill" };
            foreach (var item in list)
            {
                string[] splitString = item.Trim().Split(' ');
                int i = 0; bool IsValid = true;
                int count = 0;
                foreach (var sindividual in splitString)
                {
                    int j = CheckMatched(sindividual);
                    if (j != 0)
                    {
                        if (j > i)
                        {
                            i = j;
                            count++;
                        }
                        else
                        {
                            IsValid = false;
                        }
                    }
                }


                if (count >= 3 && IsValid)
                {
                    message += item + "   " + "yes it has t proper order \n";
                }
                else
                {
                    message += item + "   " + "Doesnt have proper order \n";
                }
            }

            lblMessage.Text = message;


        }


        int CheckMatched(string sStringtoCheck)
        {
            sStringtoCheck = sStringtoCheck.Trim().ToLower();

            if (sStringtoCheck.Contains("bill"))
            {
                return 1;
            }
            else if (sStringtoCheck.Contains("had"))
            {
                return 2;
            }
            else if (sStringtoCheck.Contains("cat"))
            {
                return 3;
            }
            else return 0;
        }

这也可以正常工作...但有点大。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接