Hi, I’m working on a problem from Code Wars and I’m a bit rusty. Basically, the task is to take an integer array of numbers and return a string in the format of a phone number, i.e. – (999) 999-9999.

In Visual Studio, my attempted solutions are returning bogus responses. My thought process is that I need to convert the int array into a char list that I can insert the ‘(‘, ‘)’, ‘ ‘, and ‘-‘ characters into at the correct indexes, and then convert this char list into a string that will be returned. The result I am getting is Unicode prefixes concatenated together. Any help or hints are appreciated!

What about using a Console.WriteLine with a format string?
int[] numbers = {1,2,3,4,5,6,7,8,9,0};
Console.WriteLine("({0}{1}{2}) {3}{4}{5}-{6}{7}{8}{9}", numbers.Select(x => x.ToString()).ToArray());

Thanks, I didn’t think of that. I often see answers written using query syntax, and I’m trying to get my brain into that sort of mindset.
One problem with your approach may be as you insert stuff, the array changes and the positions of the next inserts are no longer correct.
Also, strings are encoded in ASCII, so casting an int to char will not work.

You will gen empty or weird characters, because that’s what the numbers 0 – 9 are mapped to in ASCII. Google “ASCII table” to see how that works.
So, if you’ve figured it out, you can convert the numbers 0 – 9 to chars ‘0’ to ‘9’ by adding 48 to n to adjust it to the necessary ASCII values. This only works because the ASCII characters for 0-9 are ordered ascending also.

Basically a number is just a number, and a character displayed on screen is a number converted to some font character based on a table. e.g. the char literal '1' is actually equal to 49

As you journey through C# you will learn that strings are immutable and that adding them together like that is bad for times when you need to add a LOT of strings. It’s ok for stuff like this, but when performance is critical, you should know how things work “underneath the hood”.

Also look at the constructors for string.
https://docs.microsoft.com/en-us/dotnet/api/system.string.-ctor?view=net-5.0
In one of them, you can create a new string using an array of characters. A list of anything can be converted to an array using ToArray. Can you figure out the rest to avoid the last loop?

Thank you for the help. In addition to your suggested changes, I used: string pNumber = new string(list.ToArray()); to avoid the loop. The solution is correct.
What about this:
That also works, thanks!
Casting int to char is the problem.

I would do it like this, just because I like the ability to change the format in case of need without rewriting all the {0}{1}{2}{3}{4}{5}.
Edit: you may throw the validation part away if you’re sure that your input is always correct. I’m just a bit unfamiliar with your context, so I thought I should include it.

source