- Home /
Foreach's char loop not functioning as expected
I'm confused about chars in foreach. In Debug 1, it goes through each of the characters in currentDependency just as expected. In Debug 2, however, when the if statement passes, it always returns an index of 1, which is correct for the first |, as the first | has an index of 1, The subsequent |'s, however, should have indexes of 19 and 38 I believe, not also 1. Why does the .IndexOf(c) go back in time to the first c that passed the if statement, while the encapsulating code is for a separate character? Thanks in advance!
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...]
Answer by Larry-Dietz · Dec 01, 2019 at 07:44 PM
IndexOf return the first matching character in the string. If you want to find each one as you iterate through. Just track the position of the last one you found, and use the overload for IndexOf that takes a starting position in the string, and set it to your last position + 1
Hope this helps, -Larry
Or, alternatively, create a counter variable as in int, starting at 0, and increment it inside your loop, and use this counter for the index of the separator. Just make sure to increment it AFTER you add the index to your list.
Your answer
Follow this Question
Related Questions
Using LINQ within a foreach only runs once 1 Answer
Multiple Cars not working 1 Answer
How to get the colliders working? 1 Answer
Distribute terrain in zones 3 Answers
Not able to convert GetComponent ().netId to a string. 0 Answers