Domanda

The input is an string and a char, i.e:

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

The output should be an array of integers, i.e:

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

Here is my guess:

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();
}

Is there any way more efficient to do it?

È stato utile?

Soluzione 2

This should do it:

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

Altri suggerimenti

It's not going to get much more efficient than a loop with IndexOf inside of it.

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);
    }
}

You can call .ToArray() on the above method's results if you need to.

You can iterate through the string:

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

You can use LINQ for that:

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);
}

Or, use a simple for loop:

public static IEnumerable<int> CharPositions(string input, char match)
{
    for (int i = 0; i < input.Length; i++)
    {
       if (input[i] == match)
             yield return i;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top