Reputation: 13
I have an array of numbers in C#. The numbers range from one to ten. I would like to just show letters for example a letter "b" instead of the number 2.
Is there an easy way for me to do this.
Hope there is.
Maria
Upvotes: 1
Views: 208
Reputation: 1062745
The simplest way would be to just build a mapping array:
char[] chars = "abcdefghij".ToCharArray();
and just use:
for(int i = 0 ; i < arr.Length;i++) {
int num = arr[i]; // 1 to 10
Console.Write(chars[num-1]);
}
Upvotes: 1
Reputation: 65126
Put your letters of choice in a string and then index it with the number.
char character = "abcdefghij"[number - 1];
If you'd like to convert the entire array at once, you can easily do it using Linq:
using System.Linq;
// ...
string letters = "abcdefghij";
int[] numbers = new [] { 1, 5, 2, 7 };
string converted = new String(numbers.Select(n => letters[n - 1]).ToArray());
This takes advantage of the this constructor, which allows you to create a new string from an array of char
.
Upvotes: 2