Home > front end >  C# .IndexOf(char,int) return incorrect value
C# .IndexOf(char,int) return incorrect value

Time:03-02

I need to get index of second '.' in e-mail adres.
a)

string email [email protected] ;
int dotIndex = email.IndexOf('.');
int nextDotIndex = email.IndexOf('.',dotIndex);

result

nextDotIndex == 4   

If i make that like this:
b)

string email [email protected] ;
int dotIndex = email.IndexOf('.');
int nextDotIndex = email.IndexOf('.',dotIndex 1);

result

nextDotIndex == 14 

I know that in a) first checked element is index of first '.',but

Why in a) nextDotIndex==4, not nextDotIndex ==0 ?

CodePudding user response:

Why in a) nextDotIndex==4, not nextDotIndex ==0 ?

becuase you did

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

on this string

[email protected]
0123456789

you said start at offset 4, which is the '.'

Indexof returns the offset in the whole string, not the offset relative to the start

from the 'manual' https://docs.microsoft.com/en-us/dotnet/api/system.string.indexof?view=net-6.0#system-string-indexof(system-char-system-int32)

Returns Int32 The zero-based index position of value from the start of the string if that character is found, or -1 if it is not.

CodePudding user response:

In the first example, for the second check, it's starting looking at index 4, it checks that character, and behold, it has found the character, so it goes to return it, and it tells you what index in the string it found it at. It didn't find it at index zero, it found it at index 4. Just because it didn't check the lower numbered indexes doesn't mean they don't exist.

This is the expected behavior, you can see it in the documentation:

Documentation for String.IndexOf

CodePudding user response:

string index starts from 0.

string email = "[email protected];";
int dotIndex = email.IndexOf("."); // 4

email.Substring(dotIndex); // [email protected];

So you have to add 1, otherwise you will start from dot

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

CodePudding user response:

int index = s.IndexOf(',', s.IndexOf(',') 1); You may ensure that you're not going outofbound

CodePudding user response:

using System.Linq;

int n=2;

int nIndex= String.Join(".", email.split('.').skip(0).take(n)).length;
  • Related