一个字符的字符串C#第三索引 [英] C# third index of a character in a string

查看:167
本文介绍了一个字符的字符串C#第三索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于一个字符的字符串C#第三索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆