Home > Mobile >  C# improper result of index range expression
C# improper result of index range expression

Time:02-27

I'm slightly confused with index range operator: I expected that the expression myString[..0] should be equvalent to myString[0..0], then myString.Substring(0, 1) or myString[0].ToString(), and in case of code below:

string myString = " abc";
string resultString = myString[..0];

the resultString value should be a single space " ". Unfortunately, I got String.Empty :(

Does anybody know why and can explain me, why I'm wrong?

The Microsoft docs doesn't describe similar cases (or I can't find them).

CodePudding user response:

the resultString value should be a single space " "

No, it shouldn't.

The end of a range is exclusive, not inclusive. So for example, x[0..x.Length] will always return the whole string.

In your case, you're saying "everything before index 0" which is obviously "the empty string".

This is documented in (aside from other places) the documentation for Range.End:

Gets an Index that represents the exclusive end index of the range.

CodePudding user response:

The .. is a syntax for System.Range and the form which you are using

string resultString = myString[..0];

is translated into,

string resultString = myString[Range.EndAt(new Index(0, fromEnd: true))] 

In your case, you are trying ..0 which means all elements which are before 0th index and that is the reason you are getting result as string.Empty

MSDN documentation for Index.End Property

Gets an Index that points beyond the last element.

CodePudding user response:

It might be easier to consider the indexes in a range as being between the characters

 H e l l o   w o r l d
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6 7 8 9 10 11

The "from end" indexer ^ is the same but reversed:

   H e l l o   w o r l d
  ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
11 10 9 8 7 6 5 4 3 2 1 0

When you cut a string with ranges you get all the chars between the indexes

var hw = "Hello world";

hw[0..11]  //Hello world
hw[..5]    //Hello
hw[0..0]   //(empty string - there are no characters between index 0 and index 0)
hw[^5..]   //world
hw[^5..^1] //worl
hw[^5..10] //worl
hw[6..10]  //worl
hw[6..^1]  //worl
  • Related