C#.IndexOf(char,int)返回了不正确的值



我需要获取第二个"的索引电子邮件地址
a(

string email =john.curter@it.dev.comp.com ;
int dotIndex = email.IndexOf('.');
int nextDotIndex = email.IndexOf('.',dotIndex);

结果

nextDotIndex == 4   

如果我这样做:
b(

string email =john.curter@it.dev.comp.com ;
int dotIndex = email.IndexOf('.');
int nextDotIndex = email.IndexOf('.',dotIndex+1);

结果

nextDotIndex == 14 

我知道在a(中,第一个被检查的元素是第一个"."的索引,但是

为什么在a(中nextDotIndex==4,而不是nextDotIndex==0

为什么在a(nextDotIndex==4,而不是nextDotIndex==0?

因为你做了

int nextDotIndex = email.IndexOf('.', 4);

在这个字符串上

john.curter@it.dev.comp.com
0123456789

你说从偏移量4开始,这就是"。">

Indexof返回整个字符串中的偏移量,而不是相对于起始的偏移量

来自"手册"https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof?view=net-(system-char-system-int32(的6.0#系统字符串索引

返回Int32如果找到该字符,则从字符串开头开始的值的从零开始的索引位置,如果没有找到,则为-1。

在第一个例子中,对于第二个检查,它开始查看索引4,检查该字符,然后它找到了该字符,所以它返回该字符,并告诉您在字符串中找到了它的索引。它没有在索引0找到它,而是在索引4找到它。它没有检查编号较低的索引并不意味着它们不存在。

这是预期的行为,您可以在文档中看到:

字符串索引的文档

字符串索引从0开始。

string email = "john.curter@it.dev.comp.com;";
int dotIndex = email.IndexOf("."); // 4
email.Substring(dotIndex); // .curter@it.dev.comp.com;

所以你必须加1,否则你将从点开始

int nextDotIndex = email.IndexOf('.',dotIndex+1); //14

int index = s.IndexOf(',', s.IndexOf(',') + 1);你可以确保你不会走出边界

using System.Linq;
var email = "abc.d.ef@gh.com";
int n = 2; // the nIndex you want example 2 => 5
var tableSplit = email.Split('.');  //split by dot
var before =string.Join('.', tableSplit.Take(n)); // your rebuid precedent string  'abc.d' 
int nIndex = before.Length;// 5

最新更新