【问题标题】:Why does foreach's char loop not function as expected?为什么 foreach 的 char 循环不能按预期运行?
【发布时间】: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


【解决方案1】:

每次您找到第一个匹配项(索引 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
    }
}

【讨论】:

    【解决方案2】:

    以您自己的代码为基础,我修改了您调用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 函数将从不同的起点开始寻找所需的字符,而不是从字符串的最开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多