简体   繁体   中英

How to pad an array in C#?

I am preparing a code that splits a string into arrays of chars and then shuffles each array according to a certain pattern.

I have used some code to split an array to different char arrays according to the "keysize" and it is working fine, except for the last array which might be missing some elements.

If the last array is shorter than other arrays an exception will be thrown because at some point the swapping function might be trying to swap a[0] with a[x] which doesn't exist.

So how can I pad the last array to be the same size?

Here is my splitting code which I found in a question here, where I have edited to use char instead of int .

public static char[][] Split(char[] source, int keysize)
    {
        int fullArrayCount = source.Length / keysize;
        int totalArrayCount = fullArrayCount;
        int remainder = source.Length - (fullArrayCount * keysize);
        if (remainder > 0)
        {
            totalArrayCount++;
        }
        char[][] output = new char[totalArrayCount][];
        for (int i = 0; i < fullArrayCount; i++)
        {
            output[i] = new char[keysize];
            Array.Copy(source, i * keysize, output[i], 0, keysize); // Array.Copy(Original Array,,Target array,"Where to start"0,Howmuch)
        }
        if (totalArrayCount != fullArrayCount)
        {

            output[fullArrayCount] = new char[remainder];
           // output[fullArrayCount] = new char[keysize];
            MessageBox.Show((keysize-remainder).ToString());
            Array.Copy(source, fullArrayCount * keysize,output[fullArrayCount], 0, remainder);

        }
        return output;
    }

Can't you just instead of:

output[fullArrayCount] = new char[remainder];

write:

output[fullArrayCount] = new char[keysize];

Split an array of chars into a collection of arrays of chars of specified lengths, padded with pipe symbols that can be easily replaced/removed/searched for. (it didn't like empty char)

public static List<char[]> Split(char[] source, int keysize)
{
    List<char[]> list = new List<char[]>();

    for (int i = 0; i < source.Length; i+= keysize)
    {
        List<char> c = source.Skip(i).Take(keysize).ToList();
        while (c.Count < keysize)
        {
            c.Add('|');
        }
        list.Add(c.ToArray());
    }
    return list;
}

static void Main(string[] args)
{

    var x = Split("abcdefgh".ToCharArray(), 3);

    Console.ReadLine();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM