一个字符的字符串C#第三索引字符串、字符、索引

2023-09-03 16:11:39 作者:你不是真正的快乐゜

在那里,可以得到字符串中的字符的第三个索引的命令?例如:

is there a command that can get the third index of a character in a string? For example:

error: file.ext: line 10: invalid command [test:)]

在上面这句话,我想第三结肠指数,旁边10.我怎么能做到这一点的呢?我知道string.IndexOf和string.LastIndexOf的,但在这种情况下,我希望得到一个字符的索引时,使用它的第三次。

In the above sentence, I want to the index of the 3rd colon, the one next to the 10. How could I do that? I know of string.IndexOf and string.LastIndexOf, but in this case I want to get the index of a character when it is used the third time.

推荐答案

String.IndexOf 将让你在第一的指标,但重载给人一种起点。所以,你可以使用第一个的IndexOf 加一为出发点,为下一次的结果。然后只累积索引的足够次数:

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);

添加的错误处理,除非你知道 myString的至少包含三个冒号。

Add error handling unless you know that myString contains at least three colons.

 
精彩推荐