0
Is it possible to add an element at the end of a char array made by the method "ToCharArray"?
I want to add an element to a char array created in base of a string which is read by the console in which I use the method "ToCharArray()" is there any method or would you suggest to transform it into a list??
6 Respuestas
+ 3
If it's partially filled you can do:
myArray[capacity - 1] = myValue;
If the array is not partially filled (Which ToCharArray won't be) then you must create a new array of larger size. With the new larger partially filled array, you can append the element to the end of the array, and copy all old data over.
Or use a list.
+ 3
"Arrays are fixed size, which means you can't add more elements than the number allocated at creation time, if you need a auto sizing collection you could use List<T> or an ArrayList"
Source: https://stackoverflow.com/questions/1836959/how-to-add-to-end-of-array-c
Basically what it means, is that if your array has already reached the size you defined for it, you won't be able to add more elements to it, lists are definitely flexible so they are easily expanded.
Is there a reason why you would want to convert string to char array?
Also another link: https://www.codeproject.com/questions/595335/c-plusarraysplusversuspluslist
+ 2
Why not check length of string and simply add to the start of it, if its length is shorter than required.
string a="1234567";
if(a.length<8) a="0"+a;
+ 1
Also another way you can get characters from string is this way,
string a="123456";
int c=(int) a[0];
or by using a. left, a. right or substring to get characters.
This way you got no need of creating a list or an array.
0
Yes, it's because I need to use the digits in that list to multiply them as I do it in the code that I posted "verificación de CI o RUT uruguayo", basically it's to verify that the ID that the user inputs is valid for Uruguay, and in the case of ID number's that have 7 digit I have to add a 0 at the beginning of the full ID number to be able to verify. I have longer way to solve the problem, I'm gonna fix it in a while and I share it :)
0
perfect! Thanks Amar!!