【问题标题】:Get array with the position of a repeated char in a string获取字符串中重复字符位置的数组
【发布时间】:2014-06-23 12:25:42
【问题描述】:

输入是一个字符串和一个字符,即:

string stInput = "An string with multiple spaces";
char charInput = ' ';

输出应该是一个整数数组,即:

int[] output = CharPositions(stInput, charInput);
// output = {2, 9, 14, 23};

这是我的猜测:

int[] CharPositions(string stInput, char charInput)
{
    List<int> output = new List<int>();
    int i = stInput.IndexOf(charInput, 0);
    while(i > -1)
    {
        output.Add(i);
        i = stInput.IndexOf(charInput, i + 1);
    }
    output.Add(i);
    return output.ToArray();
}

有没有更高效的方法?

【问题讨论】:

  • 你有没有尝试过,或者你只是期待一个答案?
  • @Delta 我已经尝试过使用 string.IndexOfAny() 但它却相反。在与遇到相同问题的人进行谷歌搜索后,我什么也没找到。
  • 很难猜测一种低效的方式可能是什么样子。
  • 你需要付出更多的努力。你试过什么?这读起来像“请发送代码”
  • 我在笔记本上写了一个简单的循环,但看起来不太好。我会照你的要求复制它。

标签: c# regex string char comparison


【解决方案1】:

它不会比包含IndexOf 的循环更有效。

IEnumerable<int> CharPositions(string input, char match)
{
    int i = input.IndexOf(match, 0);
    while(i > -1)
    {
        yield return i;
        i = input.IndexOf(match, i + 1);
    }
}

如果需要,可以在上述方法的结果上调用.ToArray()

【讨论】:

    【解决方案2】:

    你可以遍历字符串:

    static IEnumerable<int> CharPositions(string input, char match)
    {
        for (int i = 0; i < input.Length; i++)
            if (input[i] == match)
                yield return i;
    }
    

    【讨论】:

      【解决方案3】:
      public static int[] IndicesOf(this string self, char match)
      {
        if (string.IsNullOrEmpty(self))
          return new int[0];
      
        var indices = new List<int>();
      
        for (var i = 0; i < self.Length; i++)
        {
          if (self[i] == match)
            indices.Add(i);
        }
      
        return indices.ToArray();
      }
      

      【讨论】:

        【解决方案4】:

        应该这样做:

        public int[] CharPositions(string input, char match)
        {
            return Regex.Matches(input, Regex.Escape(match.ToString()))
                       .Cast<Match>()
                       .Select(m => m.Index)
                       .ToArray();
        }
        

        【讨论】:

        • 你应该这样做Regex.Escape(match.ToString())
        【解决方案5】:

        您可以为此使用LINQ

        public static IEnumerable<int> CharPositions(string input, char match)
        {
           return input
                 .Select((x, idx) => new { x, idx })
                 .Where(c => c.x == match)
                 .Select(c => c.idx);
        }
        

        或者,使用简单的for 循环:

        public static IEnumerable<int> CharPositions(string input, char match)
        {
            for (int i = 0; i < input.Length; i++)
            {
               if (input[i] == match)
                     yield return i;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-12
          • 2021-03-25
          相关资源
          最近更新 更多