【问题标题】:Find a string/word inside another string在另一个字符串中查找一个字符串/单词
【发布时间】:2021-01-22 18:44:25
【问题描述】:

我发现了很多与此问题类似的帖子,但似乎找不到真正适合我的帖子。

我想检查string str = "blablatestblabla" 是否包含string str = "test"。 当有完全匹配时,我可以使用它。否则失败。 我已经尝试了几种方法来做到这一点,比如;

Regex.IsMatch()
str.Contains()
IndexOf()

这段代码的目的是找到特定的字符串(精确匹配或字符串内的匹配),将此字符串添加到一个List中,然后继续添加下面的字符串,直到找到第二个搜索字符串。

希望你能理解我的问题。

提前致谢!

编辑: 看起来很多人很难理解我的要求,所以我会尽量让事情更清楚。

假设我有一个输入List<string>包含以下内容;

fail
fail
start //Exact match (search string 1)
data 1 
data 2
end //Exact match (search string 2)
fail 
fail 

fail 
fail 
junkstartjunk //Contains "start" within the string (search string 1)
data 3
data 4
junkendjunk //Contains "end" within the string (search string 2)
fail 
fail 

无论是完全匹配还是包含匹配项 (junkstartjunk),我都无法找到搜索字符串 1(开始)。

我希望输出列表看起来像这样;

start
data 1
data 2
end

junkstartjunk
data 3
data 4
junkendjunk

这是我目前的代码:

public void FindAndRearrangeMsg(Converter converter)
    {
        List<string> txtInput = new List<string>();
        txtInput = converter.TxtInput; // Gets the user input.
        string strFindAndArrMsg1 = converter.StrFindAndArrMsg1; // Gets the first string to search for
        string strFindAndArrMsg2 = converter.StrFindAndArrMsg2; // Gets the second string to search for
        bool msg1Found = false; // Becomes TRUE if user's first string is found
        string newLine = "\n";

        foreach (string str in txtInput)
        {
            bool firstMsg = strFindAndArrMsg1.Contains(str); // User's first specific word
            bool secondMsg = strFindAndArrMsg2.Contains(str); // User's second specific word

            if (((!string.IsNullOrEmpty(str)) || (!string.IsNullOrWhiteSpace(str))) && firstMsg && msg1Found == false)
            {
                msg1Found = true;
                outputListData.Add(str.ToString()); // Add the first string
            }
            // Continue to add string between the first and the second search string.
            else if (!secondMsg && msg1Found) 
            {
                outputListData.Add(str.ToString());
            }
            //If the second search string and the first search string is found.
            else if (secondMsg && msg1Found)
            {
                outputListData.Add(str.ToString() + newLine);
                msg1Found = false;
            }
            else
            {
                msg1Found = false;
                continue;
            }
        }
    }

【问题讨论】:

  • “希望你能理解我的问题。” -- 不,一点也不。 string.Contains() 方法完全符合您似乎的要求。请修正您的问题,以便它有一个 minimal reproducible example 来准确显示您尝试过的内容。准确地解释该代码的作用以及您希望它做什么。说明具体您无法弄清楚并需要帮助的地方。
  • 如果找到文本“test”,str1.IndexOf("test") 返回大于 -1。

标签: c# contains


【解决方案1】:

看起来@Eatos 的问题陈述是正确的。但是使用单个 foreach 循环似乎更清洁。如果你在你想要的部分里面,这个问题只需要一个状态来跟踪。

我认为作为迭代器更容易。

不清楚您是否希望输入字符串包含开始/结束序列或开始/结束序列包含输入字符串。我已经在输入字符串包含开始/结束的地方完成了。

我还假设您想要包含终止的开始/结束行。如果这不是您想要的,那么修改应该是微不足道的。

    static string[] TestData = new string[]
        {
            "one","randomtwotext","three","four","five","six","seven"
        };

    static void Main(string[] _)
    {
        const string start = "two";
        const string end = "six";

        var subset = GetBetween(TestData, start, end);

        foreach (var str in subset)
            Console.WriteLine(str);
    }

    static IEnumerable<string> GetBetween(IEnumerable<string> source, string start, string end)
    {
        bool inSequence = false;

        foreach (var str in source)
        {
            if (inSequence)
            {
                yield return str;

                if (str.Contains(end))
                    break;
            }
            else if(str.Contains(start))
            {
                yield return str;
                inSequence = true;
            }
        }
    }

【讨论】:

  • 老实说,我并没有完全关注你的代码。但它似乎只检查精确匹配?我正在寻找精确匹配和字符串中的匹配。我已经更新了我的问题,希望它更容易理解。
  • @HeXxa 它正在做我认为你要求的事情。如果 str=="junkstartjunk" 那么 str.Contains("start") 将为真。如果 str=="start" 也是如此。如果您查看测试数据,您会发现它同时包含完全匹配和部分匹配。
  • 我试过你的代码,但我没有设法让它与我的代码一起工作。在 IEnumerable 方面,我是编程新手和真正的新手。但是由于您的贡献,我设法使自己的代码正常工作。谢谢。
【解决方案2】:

我相信我理解它。您想遍历一些字符串列表并创建一个新列表,该列表是第一个列表的子集,仅包含索引大于或等于包含某个给定字符串的第一个列表中的第一个字符串的条目,并继续重写值直到您在第一个列表中遇到一个包含第二个给定字符串的字符串。对吧?

如果是这样,那么我不会使用foreach 循环,它不适合这项工作。改用 2 个 while 循环(如果您不打算使用任何 LINQ 或其他)。

伪代码:

 
int i = 0;
int j = inputList.length;

// Keep ignoring list elements until we either out of bounds or found a match
while(i < j && !strFindAndArrMsg1.Contains(inputList[i])) {
 i += 1;
}

// inputList[i] - 1st item in the list that contains strFindAndArrMsg1

while(i < j && !strFindAndArrMsg2.Contains(inputList[i])) {
// keep adding values to the second list...
 i += 1;
}
// ...until we are either out ou bounds or found a second match.
// inputList[i] - 1st item in the list that contains strFindAndArrMsg2

根据边缘情况(您是否想要包含/排除第一个/第二个找到的元素)您可能需要在循环之外调整索引/添加其他值。

【讨论】:

  • 没想到while循环。可能是个好主意。但正如我在上面的答案中所写,这似乎只检查精确匹配?我正在寻找精确匹配和字符串中的匹配。我已经更新了我的问题,希望它更容易理解。
  • 必须澄清一件事:exact match => contains returns true 在完全匹配的情况下,子字符串(如果包含它,我们会在其他字符串中查找)恰好是相同的字符串.所以"a".Contains("a")"ab".Contains("a") 都会返回true。第一个是完全匹配,第二个找到一个子字符串。
  • 是的,我现在设法让我的代码工作了。我不确定我一开始在哪里搞砸了。虽然在我的示例中它应该是 strFindAndArrMsg1.Contains(str),但它应该是 str.Contains(strFindAndArrMsg1)。但我很确定我一开始就正确编码了它,但又犯了其他错误。我仍在学习 C# 编程的基础知识。谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2013-11-19
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
相关资源
最近更新 更多