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#?
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#?
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] + "\"");
}
}
尝试这个:
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 + "\"");
像这样的东西一定要喜欢 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 + "\""));
String.IndexOf()
您可以从该方法中获取从零开始的位置索引。
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;
}
尝试这个:
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++;
}