简体   繁体   English

获取两个单词C#之间的最短字符串

[英]Get Shortest String between two Words C#

I want to get the shortest string between two given words. 我想得到两个给定单词之间的最短字符串。 I can get the string between two words, but the problem happens if there is same word twice. 我可以得到两个单词之间的字符串,但是如果有两个相同的单词,则会发生问题。

Sentence: The people who were working with other people are here. 一句话:谁是与其他一起工作的 ,都在这里。

I want to get the string between the last people and here . 我想把最后的人们这里联系起来 This is the method I am currently using: 这是我目前使用的方法:

private static string Between(this string value, string a, string b)
{
    int posA = value.IndexOf(a);
    int posB = value.LastIndexOf(b);
    if (posA == -1)
    {
        return "";
    }
    if (posB == -1)
    {
        return "";
    }
    int adjustedPosA = posA + a.Length;
    if (adjustedPosA >= posB)
    {
        return "";
    }
    return value.Substring(adjustedPosA, posB - adjustedPosA);
}

This function works if there is no repeat. 如果没有重复,此功能将起作用。 But for the example it returns me all the string between the first people and here. 但是对于该示例,它返回了第一个人和此处之间的所有字符串。 How can I get the result between the last people and here? 我如何在最后一个人和这里之间得到结果? The result I am expecting is are . 我期望的结果

Use LastIndexOf When looking for both words, so that you always find the last occurence of the word. 在查找两个单词时使用LastIndexOf ,以便始终找到单词的最后一次出现。

   int posA = value.LastIndexOf(a);
   int posB = value.LastIndexOf(b);

However: this might not produce what you want for "The people who were working here with other people". 但是:这可能无法满足“与其他人一起工作的人”的需求。 Please clarify your requirements 请说明您的要求

Other Solution using regular expressions at https://stackoverflow.com/a/35105389/101087 使用正则表达式的其他解决方案, 网址https://stackoverflow.com/a/35105389/101087

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM