Почему цикл foreach не работает должным образом? - PullRequest
0 голосов
/ 01 декабря 2019

Я запутался насчет символов в foreach. В Debug 1 он проходит все символы в currentDependency, как и ожидалось. Однако в Debug 2, когда оператор if проходит, он всегда возвращает индекс 1, который является правильным для первого |, в качестве первого |имеет индекс 1, однако последующие | должны иметь индексы 19 и 38, я полагаю, не также 1. Почему .IndexOf (c) возвращается во времени к первому c, который передал оператор if,в то время как инкапсулирующий код для отдельного символа? Заранее спасибо!

string currentDependency = ">|Policies/Tax/-0.3|Policies/Trade/0.3|Power/Trader:Farmer/0.4";

foreach (char c in currentDependency)//add spots of separations of sections
{
    Debug.Log("CurrentChar: " + c.ToString());//DEBUG 1

    if (c.ToString().Contains("|"))
    {
        sectionsSpots.Add(currentDependency.IndexOf(c));

        Debug.Log("| found in string, index of " + currentDependency.IndexOf(c));//DEBUG 2
    }
}

//Output:
//CurrentChar: >
//CurrentChar: |
//| found in string, index of 1
//CurrentChar: P
//CurrentChar: o
//[...]
//CurrentChar: 3
//CurrentChar: |
//| found in string, index of 1////!!Why is the index of 1, rather than of 19?!!////
//[and so on...]

Ответы [ 2 ]

3 голосов
/ 01 декабря 2019

Каждый раз, когда вы находите первое вхождение (индекс 2). см.: https://docs.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netframework-4.8; Самый простой способ достичь цели:

for (int i = 0; i < currentDependency.Length; i++)
{
    if (currentDependency[i] == '|')
    {
        sectionsSpots.Add(i);
        Debug.Log("| found in string, index of " + i);//DEBUG 2
    }
}
0 голосов
/ 01 декабря 2019

Используя ваш собственный код в качестве основы, я изменил способ вызова функции IndexOf, чтобы использовать другие ее параметры.

List<Int32> sectionsSpots = new List<Int32>();
string currentDependency = ">|Policies/Tax/-0.3|Policies/Trade/0.3|Power/Trader:Farmer/0.4";

Int32 startPosition = 0;

foreach (char c in currentDependency)//add spots of separations of sections
{
    Debug.Print("CurrentChar: " + c.ToString());//DEBUG 1

    if (c.Equals('|'))
    {
        Int32 position = currentDependency.IndexOf(c, startPosition);
        sectionsSpots.Add(position);

        Debug.Print("| found in string, index of " + position);//DEBUG 2

        startPosition = position + 1;
    }
}

Передав position, IndexOfФункция начнет поиск нужного символа с другой начальной точки, а не с самого начала строки.

...