【发布时间】:2020-03-26 11:48:53
【问题描述】:
在我的 foreach 循环中,char 'c' 表征字符串 currentDependency 中的每个字符,如果 c 是 '|',那么它将 this 的位置添加到 ListsectionsSpots。但是,它似乎循环遍历已经找到的字符,这意味着我可能不明白循环方法是如何工作的。
在 Debug 1 中,它按预期遍历 currentDependency 中的每个字符。然而,在调试 2 中,当 if 语句通过时,它总是返回索引 1,这对于第一个 | 是正确的,就像第一个 |索引为 1,后续 | 的索引应为 19 和 38。为什么 .IndexOf(c) 返回到 if 语句中传递的第一个 c,而代码实际上应该在后面测量字符细绳?提前致谢!
string currentDependency = ">|Policies/Tax/-0.3|Policies/Trade/0.3|Power/Trader:Farmer/0.4";
List<int> sectionSpots = new List<int> { };
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, if I already made it through the previous | with an index of 1?
//[and so on...]
【问题讨论】:
-
来自 String.IndexOf Method 的 MSDN 页面 -
Reports the zero-based index of the first occurrence- 您将从字符串的开头重新开始 -
if (c =='|') 比 if (c.ToString().Contains("|")) 条件更好
-
看看
string.Split("|") -
当您的代码无法按预期工作时,请务必检查文档以确保您的期望与现实保持一致。请注意,有一个重载(“版本”)需要一个偏移量来从那里找到下一个字符
标签: c# string foreach char indexof