-1

I have

string input = "XXXX-NNNN-A/N";
string[] separators = { "-", "/" };

I need to find out the position of occurrence of the seperators in the string.

The output will be

5 "-" 
10 "-"
12 "/"

How to do in C#?

Henrik
  • 22,966
  • 6
  • 40
  • 91
priyanka.sarkar
  • 24,638
  • 42
  • 119
  • 168

6 Answers6

2
for (int i = 0; i < input.Length; i++)
{
    for (int j = 0; j < separators.Length; j++)
    {
        if (input[i] == separators[j])
            Console.WriteLine((i + 1) + "\"" + separators[j] + "\"");
    }
}
linquize
  • 19,090
  • 9
  • 57
  • 80
1

you can get a zero-based position index from the String.IndexOf() method.

Wim Ombelets
  • 4,725
  • 3
  • 39
  • 51
1
List<int> FindThem(string theInput)
{
    List<int> theList = new List<int>();
    int i = 0;
    while (i < theInput.Length)
        if (theInput.IndexOfAny(new[] { '-', '/' }, i) >= 0)
        {
            theList.Add(theInput.IndexOfAny(new[] { '-', '/' }, i) + 1);
            i = theList.Last();
        }
        else break;
    return theList;
}
ispiro
  • 25,277
  • 32
  • 126
  • 258
1

Try this:

string input = "XXXX-NNNN-A/N";
char[] seperators = new[] { '/', '-' };
Dictionary<int, char> positions = new Dictionary<int,char>();
for (int i = 0; i < input.Length; i++)
    if (seperators.Contains(input[i]))
        positions.Add(i + 1, input[i]);

foreach(KeyValuePair<int, char> pair in positions)
    Console.WriteLine(pair.Key + " \"" + pair.Value + "\"");
Martin Mulder
  • 12,142
  • 3
  • 22
  • 52
1

Gotta love LINQ for stuff like this. Given this:

string input = "XXXX-NNNN-A/N";
string[] separators = {"-", "/"};

Perform the search using:

var found = input.Select((c, i) => new {c = c, i = i})
            .Where(x => separators.ToList().Contains(x.c.ToString()));

Output it for example like this:

found.ToList().ForEach(element => 
                        Console.WriteLine(element.i + " \"" + element.c + "\""));
Kjartan
  • 17,961
  • 15
  • 70
  • 90
  • Or just `("XXXX-NNNN-A/N".Select((c, i) => new { c = c, i = i }).Where(x => (new[] { "-", "/" }).ToList().Contains(x.c.ToString()))).ToList().ForEach(element => Console.WriteLine(element.i + " \"" + element.c + "\""));` :) – ispiro May 03 '13 at 14:31
  • Yes, possible, of course. I was, however, trying to be slightly more pedagogical here. ;) – Kjartan May 03 '13 at 14:36
0

Try this:

int index = 0;                                                  // Starting at first character
char[] separators = "-/".ToCharArray();
while (index < input.Length) {
    index = input.IndexOfAny(separators, index);              // Find next separator
    if (index < 0) break;
    Debug.WriteLine((index+1).ToString() + ": " + input[index]);
    index++;
}
joe
  • 7,779
  • 8
  • 49
  • 75