-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
  • 23,186
  • 6
  • 42
  • 92
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173

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,828
  • 10
  • 59
  • 83
1

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

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55
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
  • 26,556
  • 38
  • 136
  • 291
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,642
  • 3
  • 25
  • 54
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
  • 18,591
  • 15
  • 71
  • 96
  • 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
  • 8,344
  • 9
  • 54
  • 80