如何在C#中找到字符出现的位置?

时间:2013-05-03 13:17:29

标签: c#

我有

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

我需要找出字符串中分隔符出现的位置。

输出

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

如何在C#中做?

6 个答案:

答案 0 :(得分: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] + "\"");
    }
}

答案 1 :(得分:1)

您可以从String.IndexOf()方法获得基于零的位置索引。

答案 2 :(得分: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;
}

答案 3 :(得分: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 + "\"");

答案 4 :(得分: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 + "\""));

答案 5 :(得分: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++;
}