0

编辑:正如 Damien_The_Unbeliever 所说,为了让这个问题更容易理解,最终结果是试图“在序列中搜索子序列”。Blue,Yellow,GreencolorsToFind内部找到序列colorList

有没有人有一些指针来确定嵌套 for 循环的最佳方法,其中内部循环需要确定父循环中是否包含一系列字符串?

因此,对于下面的示例,由于在索引 [5]​​、[6]、[7] 处可以找到“Blue”、“Yellow”、“Green”,因此我想返回这些索引。或者至少是 [5] 的第一个找到的索引。

我认为问题与for (int j循环如何在找到的索引上爆发有关。

string[] colorList = "Royal Blue", "Tomato Red", "Mustard Yellow", "Midnight Blue", "Blue", "Blue", "Yellow", "Green", "Red", "Evergreen", "Purple", "Black", "Jet Black";

string name = "Blue,Yellow,Green";

string[] colorsToFind = name.Split(',');
int found = 0;

for (int i = 0; i < colorList.Count -1; i++)
{
    for (int j = 0; j < colorsToFind.Count; j++)
    {
        if (colorList[i] == colorsToFind[j])
        {
            found = i;
            break;
        }
    }
}

if(found != 0)
{
    return found;
}

return null;
4

3 回答 3

0

当您的意思是比较发生时,您正在测试是否相等。

if (colorList[i].indexOf(colorsToFind[j]) != -1)
{
    found = i;
    break;
}
于 2012-11-30T18:42:17.197 回答
0
string[] colorList = {"Royal Blue", "Tomato Red", "Mustard Yellow", "Midnight Blue", "Blue", "Blue", "Yellow", "Green", "Red", "Evergreen", "Purple", "Black", "Jet Black"};
string[] colorsToFind = "Blue,Yellow,Green".Split(',');

for (int i = 0; i < colorList.Length - colorsToFind.Length; i++)
{
    int j;  // we'll need this later
    for (j = 0; j < colorsToFind.Length; j++)
    {
        if (colorList[j + i] != colorsToFind[j])
        {
            break;  // stop if it doesn't match
        }
    }

    // j for-loop was exited because j == colorsToFind.Length so a set matched
    if (j == colorsToFind.Length)
    {
        Console.WriteLine(i);
        break;
    }
}
于 2012-11-30T18:49:13.677 回答
0
for (int i = 0; i < colorList.Count -3; i++)
{
     if (colorList[i] == colorsToFind[0] && 
         colorList[i+1] == colorsToFind[1] && 
         colorList[i+2] == colorsToFind[2])
     {
            found = i;
            break;
     }
}

for (int i = 0; i < colorList.Count - colorsToFind.count; i++)
{
    for (int j = 0; j < colorsToFind.Count; j++)
    {
        bool match = true;
        if (colorList[i+j] != colorsToFind[j])
        {
            match = false;
        }  
    }
    if (match) 
    {   
        found = i;
        break;
    }
}
于 2012-11-30T18:53:47.733 回答