Substrings, search lists
I have a list that is populated with user-entered strings. I have already verified that the string is not empty and that the list does not contain that string.
The problem I ran into was to check if the user entered string was a string from a string in a list.
List<string> stringlist = new List<string>();
int index = 0;
string userinput = null;
while (userinput != "end")
{
userinput = getstring();
if (stringlist.Contains(userinput))
{
Console.WriteLine(" Term has been stored previously.");
}
else
{
stringlist.Insert(index, userinput);
index += 1;
}
foreach (string s in stringlist)
{
Console.WriteLine("List contains : {0}", s);
if (s.Contains(userinput))
{
// something?
}
}
} // end of main while loop
So, in principle, if the term someone introduces is "dog", if one of the other strings entered is "bigdog", it should say "dog is a substring of bigdog" or something similar. Should I use a different loop type for this?
source to share
To summarize each tip:
- Check substrings before adding an entry to the list
- Use a method
String.Contains()
to check a substring for each item in a list -
Use a method
List.Add
and then use memory in a variableindex
List<string> stringlist = new List<string>(); string userinput = null; while (userinput != "end") { userinput = getstring(); // Check for Substrings foreach (string s in stringlist.Where(s => s.Contains(userinput))) { Console.WriteLine("{0} is a substring of {1}", userinput, s); } // Add to the list if (stringlist.Contains(userinput)) { Console.WriteLine(" Term has been stored previously."); } else { stringlist.Add(userinput); } } // end of main while loop
You can use the Regex
(Regular Expressions) class to find matches in a list, but it still requires a loop foreach
, and String.Contains
will actually outperform for simple substring searches Regex.IsMatch
. I also tried to concatenate a long string list and search there in the same line of code, but this is highly susceptible to false positives as some individual entries can create new words when concatenated.
source to share