Reputation: 256
Want to add an element at a certain position of a char array. Tried to use Concat but showed error, maybe some reference was missing. Also tried to find similar question but found none.
Please see following code and to add element at the end of the array and also at any index of that array.
char[] c = { 'a','b','c','d' };
//add elements.
// c.Concat//c.add//[c.Length] = 'e';
Thanks.
Upvotes: 2
Views: 4320
Reputation: 15559
You can try this:
var myList = new char[] { 'a','b','d','e' }.ToList();
myList.Insert(2, 'c');
// View the results: "a,b,c,d,e"
Upvotes: 2
Reputation: 37377
Array has this disadvantage, that it has fixed size and in order to add elements you have to resize it, which is inconvinient.
I would suggest you to use some collection, like List
to perform such operations.
For example:
List<char> chars = new List<char>{ 'a','b','c','d' };
// add character at the end
chars.Add('e');
You can read more here.
Upvotes: 1
Reputation: 17819
The array size is static, so you can't add elements to it. However, if you really, really want to insert an element into it, you can resize the array, then shift the elements from the desired position one place to the right, and then set the new element. For example you can have this function:
public static void InsertInArray(ref char[] array, char element, int pos)
{
// Check that index is inside the bounds
if (pos < 0 || pos > array.Length)
{
throw new IndexOutOfRangeException();
}
// Resize the array
Array.Resize(ref array, array.Length + 1);
// Shift elements one place to the right, to make room to new element
for (int i = array.Length - 1; i > pos; i--)
{
array[i] = array[i-1];
}
// Set new element
array[pos] = element;
}
Then, for example:
public static void Main()
{
var myChars = new char[] { 'b', 'c', 'e' };
// Insert in position 0
InsertInArray(ref myChars, 'a', 0);
// Print array: a,b,c,e
Console.WriteLine(string.Join(",", myChars));
// Insert in position 3
InsertInArray(ref myChars, 'd', 3);
// Print array: a,b,c,d,e
Console.WriteLine(string.Join(",", myChars));
// Insert in position 5
InsertInArray(ref myChars, 'f', 5);
// Print array: a,b,c,d,e,f
Console.WriteLine(string.Join(",", myChars));
}
Full example: https://dotnetfiddle.net/pLhTzP
Upvotes: 4
Reputation: 148
use somthing like this:
var list = c.ToList();
list.Insert(int index, char item)
Upvotes: 0