Utilize C# 8 indices and ranges

Viewed 139

I am trying to solve an online challenge in an efficient way. I have to basically output a string in a certain format given an array of int.

I have to make the string look like : (123) 456-7890 (the input array is guaranteed to be correct length).

I found out about the new C# indices and ranges and tried something like this:

public static string GenerateOutput(int[] numbers)
{
    return $"({numbers[0..2]}) {numbers[3..5]}-{numbers[6..9]}";
}

But that doesn't return the desired result. How can I transform them to strings and return the correct output?

2 Answers

The main problem is that you're putting in arrays inside the string. ToString() on an array will result a string describing the type, not a string of its values. You need to concatenate those arrays. You can create a local function to make it more convenient to use:

string getNums (int start, int end) =>
    string.Join("", numbers[start..end]);

Outside of that, your indexing is inclusive on both ends. But according to Microsoft:

A range specifies the start and end of a range. Ranges are exclusive, meaning the end isn't included in the range.

That's not what exclusive means. c-sharpcorner puts it better:

The Range operator .. specifies the start (Inclusive) and end (exclusive) of a range.

I imagine they had a reason for this, but it is a very surprising choice from my perspective.

Regardless, with this in mind, you can implement the local function like this:

var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

string getNums (int start, int end) =>
    string.Join("", numbers[start..end]);

return $"({getNums(0,3)}) {getNums(3,6)}-{getNums(6,10)}";

It'd be a lot more useful if your numbers were a string so they could be ranged directly:

var s = string.Join("", numbers);

Now you can cut your string up using ranges:

var ph = $"(s[..3]}) {s[3..6]}-{s[^4..]}";
Related