How can I insert a string between two strings if a condition is true?
Let's say we have an array of characters that we want to check if the first word ends with one of them and the second word starts with one of them.
For example "Go home" will pass the condition because "o" and "h" are letters that will meet requirement (=> Go ___ home)
char[] toCheck = {'h','o','d', 'g'};
string sentence = "Go home";
List<string> words = sentence.Split(' ').ToList();
for (int i = 0; i < words.Count - 1; i++)
{
if (toCheck.Any(x=> x == words[i][words[i].Length - 1]) &&
(toCheck.Any(x=> x == words[i + 1][0])))
{
words.Insert(i,"_between");
}
}
return words.Aggregate("", (current, word) => current + (word + " "));
My problem is that this is returning "_between Go _between home" instead of "Go _between home" and I can't find out why.
Thank you for your help.
Here's a method you could use to do this that will return a sequence of the words instead of inserting into the original collection.
private static IEnumerable<string> InsertBetween(
this IList<string> words,
char[] characters,
string insertValue)
{
for (int i = 0; i < words.Count - 1; i++)
{
yield return words[i];
if (characters.Contains(words[i].Last()) && characters.Contains(words[i + 1][0]))
yield return insertValue;
}
if (words.Count > 0)
yield return words[words.Count - 1];
}
Then running this
char[] toCheck = { 'h', 'o', 'd', 'g' };
string sentence = "Go home";
Console.WriteLine(string.Join(" ", sentence.Split().InsertBetween(toCheck, "_between")));
Will give you
Go _between home
I just think it's better to avoid mutating a colleciton that you are looping over, but if you do you need to increment the index when you do an insert so you move past the inserted value and you have to insert in the correct position.
for (int i = 0; i < words.Count - 1; i++)
{
if (toCheck.Any(x => x == words[i][words[i].Length - 1]) &&
(toCheck.Any(x => x == words[i + 1][0])))
{
words.Insert(i + 1, "_between");
i++;
}
}