【发布时间】: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。