I need to check if the string on my list are found on the text to search
and how many string on the list are found
this is my string to search
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy
text ever since the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.
this is my list
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the
printing and typesetting
industry. Lorem Ipsum has been the
industry's standard dummy
text ever since the 1500s, when
an unknown printer took a galley
I created a sample code
string longString = "word1, word2, word 3";
List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });
for (int i = 0; i < myList.Count; i++)
{
if (myList.Any(str => longString.Contains(str)))
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("fail!");
}
}
But it prints the success
three times. it should be once only. How can i make this work? How can i skip the item that are already used to search the item.
It prints success three times because your are looping in myList . Try like this:
string longString = "word1, word2, word 3";
List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });
if (myList.Any(str => longString.Contains(str)))
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("fail!");
}
replace
if (myList.Any(str => longString.Contains(str)))
with
if (longString.Contains(myList[i]))
to check item by item if it exists in your string.
Your current version checks 3x if any of those items exists which is always true fore the case word 3
To get the count, you can use the following:
string longString = "word1, word2, word 3";
List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" });
int count = myList.Count(s => s.Any(a => longString.Contains(s)));
change for cycle to:
foreach (string check in myList)
{
if (longString.Any(str => longString.Contains(check)))
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("fail!");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.