-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#?

4

6 回答 6

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] + "\"");
    }
}
于 2013-05-03T13:23:01.420 回答
1

尝试这个:

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 + "\"");
于 2013-05-03T13:25:06.813 回答
1

像这样的东西一定要喜欢 LINQ。鉴于这种:

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

使用以下命令执行搜索:

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

例如像这样输出它:

found.ToList().ForEach(element => 
                        Console.WriteLine(element.i + " \"" + element.c + "\""));
于 2013-05-03T14:22:52.723 回答
1

String.IndexOf()您可以从该方法中获取从零开始的位置索引。

于 2013-05-03T13:19:26.353 回答
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;
}
于 2013-05-03T13:19:59.157 回答
0

尝试这个:

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++;
}
于 2013-05-03T13:23:34.310 回答