Simple. Iterate over all strings inside List and then check if myString
contains that or not. If yes, then replace it.
foreach (string item in lst)
{
if (myString.Contains(item))
{
myString = myString.Replace(item, string.Format("$${0}$$", item));
}
}
Also you can do same with LINQ:
lst.Where(item=> myString.Contains(item)).ToList()
.ForEach(item => myString = myString.Replace(item, string.Format("$${0}$$", item)));
You can also split string by spaces, and check if they exist in List or not:
myString.Split(' ').ToList()
.Where(x => lst.Contains(x)).ToList()
.ForEach(item => myString = myString.Replace(item, string.Format("$${0}$$", item)));
Case insensivity:
Change Contains(x)
to Contains(x, StringComparer.OrdinalIgnoreCase)
.
For example the third method:
myString.Split(' ').ToList()
.Where(x => lst.Contains(x, StringComparer.OrdinalIgnoreCase)).ToList()
.ForEach(item => myString = myString.Replace(item, string.Format("$${0}$$", item)));
8
solved Replace a string in string that is in a List