C# third index of a character in a string
String.IndexOf
will get you the index of the first, but has overloads giving a starting point. So you can use a the result of the first IndexOf
plus one as the starting point for the next. And then just accumulate indexes a sufficient number of times:
var offset = myString.IndexOf(':');
offset = myString.IndexOf(':', offset+1);
var result = myString.IndexOf(':', offset+1);
Add error handling unless you know that myString
contains at least three colons.
You could write something like:
public static int CustomIndexOf(this string source, char toFind, int position)
{
int index = -1;
for (int i = 0; i < position; i++)
{
index = source.IndexOf(toFind, index + 1);
if (index == -1)
break;
}
return index;
}
EDIT: Obviously you have to use it as follows:
int colonPosition = myString.CustomIndexOf(',', 3);
I am guessing you want to parse that string into different parts.
public static void Main() {
var input = @"error: file.ext: line 10: invalid command [test (: ]";
var splitted = input .Split(separator: new[] {": "}, count: 4, options: StringSplitOptions.None);
var severity = splitted[0]; // "error"
var filename = splitted[1]; // "file.ext"
var line = splitted[2]; // "line 10"
var message = splitted[3]; // "invalid command [test (: ]"
}