使用索引查找字符串中单词的开头和结尾

Find the start and end of a word in a string using index of

我有 2 个字符串。我使用 foreach 循环将每个字符放入一个列表中。然后我使用 for 循环遍历 2 个列表中的每个字符以查看是否存在差异。一旦我发现字符串之间的差异,我想找到那个已经改变的单词的开头和结尾,例如。 String1String2 不同 我希望输出为“String1 String2 is the first second string"。我计划使用 indexOf 查找已更改单词的开头和结尾,目前还没有查找索引的位置。

  static void Main(string[] args)
    {

        const string a = "String1 is the first string";
        const string b = "String2 is the second string";
        List<String> listString1 = new List<string>();
        List<String> listString2 = new List<string>();
        foreach (var item in a)
        {
            listString1.Add(item.ToString());
        }

        foreach (var item in b)
        {
            listString2.Add(item.ToString());
        }
        for (int i = 0; i < a.Length; i++)
        {
            var or = listString1[i];
            var ed = listString2[i];

            int nextSpace = or.IndexOf(' ', index);
            int previousSpace = or.LastIndexOf(' ', index);
            if (or!=ed)


            {

                Console.WriteLine();
            }
        }

    }

基本happy-path解决方案..

string newString = "";

string[] as1 = "String1 is the first string".Split(new char[] { ' ' });
string[] as2 = "String2 is the second string".Split(new char[] { ' ' });

for (int ndx = 0; ndx < as1.Length; ndx++)
{
    newString += (as1[ndx] == as2[ndx]) ? as1[ndx] : as1[ndx] + ' ' + as2[ndx];
    newString += ' ';
}

您至少需要对数组进行边界检查。但我不会为你做所有的功课:)

老实说,我对您要实现的目标感到困惑。但也许我所提供的是正确的道路。

static void Main(string[] args)
{
    string firstString = "I am the first string";
    string secondString = "I am the second string";

    char delimiter = Convert.ToChar(" ");

    if (firstString.Equals(secondString))
    {
        Console.WriteLine("Both strings are equal");
        Console.ReadLine();
    }
    else
    {
        var firstStringList = firstString.Split(delimiter).ToList();

        // ["I", "am", "the", "first", "string"]

        var secondStringList = secondString.Split(delimiter).ToList();

        // ["I", "am", "the", "second", "string"]

        foreach (var word in firstStringList)
        {
            if (secondStringList.IndexOf(word) == -1)
            {
                var indexOfWord = firstStringList.IndexOf(word); // 3
                secondStringList.Insert(indexOfWord, word); // Insert the word that was not found at position 3 inside secondStringList
                // ["I", "am", "the", "first", "second", "string"]
                // [ 0,    1,    2,      3,        4,         5  ]
                Console.WriteLine(string.Join(" ", secondStringList));
                // Join the secondStringList to make 1 string separated by the space character
                Console.ReadLine();
            }
        }

    }
}

此代码会将第一个字符串和第二个字符串拆分为包含组成字符串的单词的字符串列表。然后将遍历第一个字符串列表并将该列表中的每个单词与第二个中的单词进行比较字符串列表.. 一旦它在第一个字符串中找到第二个字符串中不存在的单词.. 它将打印该单词。

同样,不确定这样做的目的,但请根据我发布的内容告诉我需要定制的内容。