1

嗨,我有一个字符串“abc %d ef %g hi %j”。我想得到“%”的索引。它应该给出第一次出现的索引,即 3。有人可以给我一个 C# 片段吗?

提前致谢

4

5 回答 5

4

片段是:

int firstOccurence = "abc %d ef %g hi %j".IndexOf("%");
//  firstOccurence will be 4
于 2013-01-31T11:39:25.133 回答
3

返回的索引将为 4。C# 具有从零开始的索引。

string foo = "abc %d ef %g hi %j";
int i = foo.IndexOf("%"); // Returns 4

资源:

String.IndexOf()在 MSDN 上查看。

笔记:

帮自己一个忙,看看 whathaveyouried.com和 StackOverflow 的常见问题解答。这将使您在这里的体验更加有趣!

于 2013-01-31T11:39:54.433 回答
1

尝试这个:

string str = "abc %d ef %g hi %j";
int index = str.IndexOf('%');

String.IndexOf 方法

于 2013-01-31T11:40:16.613 回答
0

LINQ版本

string str = "abc %d ef %g hi %j";
var ind = str.Select((item, index) => new  { Found = item,  Index = index }).Where(it => it.Found=='%').Select( it => it.Index).First();
于 2013-01-31T11:54:59.867 回答
0
string x = "bc %d ef %g hi %j";
int y = x.IndexOf('%');
于 2013-01-31T11:40:47.553 回答