检查字符串数组中的单词是否以 char 结尾和开头,并在它们之间插入新字符串 (c#)

Check if words in string array ends and starts with char and insert new string between them (c#)

如果条件为真,如何在两个字符串之间插入一个字符串?

假设我们有一个字符数组,我们想要检查第一个单词是否以其中一个结尾,第二个单词是否以其中一个开头。

例如"Go home"会通过条件,因为"o"和"h"是满足要求的字母(=>去___家)

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 + " "));

我的问题是返回的是“_between Go _between home”而不是 "Go _between home",我不知道为什么。

感谢您的帮助。

考虑将生成的句子存储在新的 string:

中,这是一种非常直接的方法
char[] toCheck = { 'h', 'o', 'd', 'g' };
string sentence = "Go home";

string finalsentence = "";

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]))) {
             finalsentence = words[i] + "_between" + words[i + 1] + " ";
    }
}

return finalsentence;

也就是说,如果你想用你当前的方法的话,你应该参考插入索引 i + k(从 1 开始递增 k,感谢 juharr ) 而不是 i 并使用 string.Join,而不是 aggregate:

char[] toCheck = { 'h', 'o', 'd', 'g' };
string sentence = "Go home";
int k = 1;

List<string> words = sentenc;e.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 + k++, "_between");
    }
}

return string.Join(" ", words);

"My problem is that this is returning "_between Go _between home" 而不是 "Go _between home" 我不知道为什么。"

因为你的 i index in words.Insert(i,"_between"); 是从 0 开始的。你可以通过多种方式更改代码,但是根据你的问题,如果你想保留它,就不要 words.Insert(i,"_between"); 对于 i==0.

希望这对您有所帮助...

您可以使用以下方法执行此操作,该方法将 return 单词序列而不是插入到原始集合中。

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];
} 

然后运行这个

char[] toCheck = { 'h', 'o', 'd', 'g' };
string sentence = "Go home";
Console.WriteLine(string.Join(" ", sentence.Split().InsertBetween(toCheck, "_between")));

会给你

Go _between home

我只是认为最好避免改变正在循环的集合,但是如果这样做,则需要在执行插入时增加索引,这样您就可以越过插入的值,并且必须插入正确的位置。

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++;
    }
}