How to create an array containing a range of characters in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public class CharacterRangeArray
{
    public static char[] CreateCharacterRangeArray(char startChar, char endChar)
    {
        if (endChar < startChar) {
            throw new ArgumentException("End character must be greater than or equal to start character.");
        }

        return Enumerable.Range(startChar, endChar - startChar + 1)
                         .Select(i => (char)i)
                         .ToArray();
    }

    public static void Main(string[] args)
    {
        char[] charArray = CreateCharacterRangeArray('a', 'm');

        Console.WriteLine(string.Join(", ", charArray));
    }
}



/*
run:

a, b, c, d, e, f, g, h, i, j, k, l, m

*/

 



answered Mar 21, 2025 by avibootz
...