Save an unknown sized array from unknown string length

Related searches

I'd like to save input of an unknown string length into an array. How do I make so that it will result like following:

string a = "ABCA";
char[] array;
array = a.ToCharArray(0, a.length);

foreach (char c in array) {
    switch(c) {
       case 'A':
       into2ndarray = 1;
       break;

       case 'B':
       into2ndarray = 2;
       break;

       case 'C':
       into2ndarray = 3;
       break;
     }
}

int[] into2ndarray //the result will be used for another calculation

So, the expected result from this is {1, 2, 3, 1} Any idea on how to achieve this? thank you.

You can try Linq for querying, e.g.

  using System.Linq;

  ...

  int[] into2ndarray = a
    .Select(item =>       // for each character in a string
         item == 'A' ? 1  // map A to 1
       : item == 'B' ? 2  // -/- B to 2
       : item == 'C' ? 3  // -/- C to 3
       : -1)              // map other characters to -1
    .Where(number => number >= 0) // filter out -1s
    .ToArray();           // materialize as an array     

How to declare a string array of unknown size to get it from the user , Originally Answered: How do I declare a string array of unknown size to How can I write a C program to take input of two arrays a [5] and b [5]� Without further context of what you’re trying to achieve, it’s hard to answer your question properly. For example, I can pass around an arbitrary data structure in C++ by simply taking its address and casting to [code]void *[/code].

Here is how I would do that:

class Program
{
    static void Main(string[] args)
    {
        int[] array = ConvertStringToArray("ABCA");
    }

    public static int[] ConvertStringToArray(string str)
    {
        int[] array = new int[str.Length];

        for (int i = 0; i < str.Length; i++)
        {
            switch (str[i])
            {
                case 'A':
                    array[i] = 1;
                    break;

                case 'B':
                    array[i] = 2;
                    break;

                case 'C':
                    array[i] = 3;
                    break;
                default:
                    throw new NotImplementedException($"Char '{str[i]}' is not managed");
                    break;
            }
        }

        return array;
    }
}

How to read an input array when the size is not known, //Input read in str[] array with no size defined How do I Write down a program to input 10 numbers in array and to find their sum? apply any of the two methods above used to declare an array of unknown size and then use while(cin>>n) . The elements in an array may not be of the same type. As you can see, arrays in JavaScript are very flexible, so be careful with this flexibility :) There are a handful of methods to manipulate arrays like .pop(), .push(), .shift(), .unshift() etc.

Going your way

string a = "ABCA";
char[] array;
array = a.ToCharArray(0, a.length);

int[] into2ndarray = new int[array.Length]; //the result will be used for another calculation; initialized by length of the original str.
int i = 0; // Counter to save your element
foreach (char c in array) {
    switch(c) {
       case 'A':
       into2ndarray[i] = 1;    // Access the current element by index;
       break;

       case 'B':
       into2ndarray[i] = 2;
       break;

       case 'C':
       into2ndarray[i] = 3;
       break;
     }
     i++; // Increase the counter
}

but, personally, I'd go for:

    into2ndarray = array.Where(c => c <= 'C').Select(c=> (int)(c - 'A') + 1).ToArray();

importing csv array of unknown size, characters, importing csv array of unknown size, characters. I need to import each run into a different array (so a cell works well). In the case of doing the above, you would also need to store the size of each run in an array (like I do with the runs array), MATLAB > Language Fundamentals > Data Types > Characters and Strings� The problem I am encountering is that I don't if it's possible to add data to an array before its length has been declared (and thus the array isn't even instantiated), and I can't have extra elements at the end; nor can I be short on elements - its length must be exactly equal to the number of matches in the text file.

You can do this to achieve the result you want. See my comments in the code to understand what it's doing.

string a = "ABCA";

// this code is unnecessary because the characters of a string can already be accessed by index
// char[] array;
// array = a.ToCharArray(0,a.length);

int[] into2ndarray = new int[a.Length]; // instantiate the new array to the same length as the string

for (int i = 0; i < a.Length; ++i) // don't use a foreach since we need to know the index. a for loop is better here
{
    switch(a[i]){ // access the char from the string directly by index
       case 'A':
       into2ndarray[i] = 1; // assign result to the new array
       break;

       case 'B':
       into2ndarray[i] = 2;
       break;

       case 'C':
       into2ndarray[i] = 3;
       break;
  }

}

How do I initialize an array of unknown dimension?, Learn more about matlab array initialization. But how do I do that since I do not know what is the size going to be. right click and to tell MATLAB to not show that warning. store the arrays in a preallocated cell array: this is� Coder: Array dimensions must be known at compile time. To get variable dimensions, use std::vector. struct TransType //box for holding transition function data

var a = "ABCA";
var into2ndarray = a.Select(c => (int)c -'A' + 1).ToArray();

How to Create an array with unknown size? : cprogramming, I don't know how to initialize an array with unknown size. Finally, if you wanted an array-like structure to store an undetermined amount of values you may be Program that reads a string from the input and converts to integer, stops when it� Therefore, the array will never be larger than 4e6 in length. So preallocate r to be of size 1x4e6. Now just index into the array, keeping a running count of where you stuffed the last elements into the array. At the end, just delete the unused elements. I would pre-allocate with NaNs, so you know what was unused. Preallocate a cell array instead.

I now know how slices work but at the end of the day, I still had an array that would have to grow. I was taught in school that linked lists were more efficient and gave you a better way to store large collections of data. Especially when the number of items you need to collect is unknown. It made sense to me.

All dimensions but the left-most must be known at compile time in order to pass an actual array. (You're not actually passing an array, you're passing an array that has decayed to a pointer.) You can also allocate a big chunk of contiguous memory and pretend that it's a 2D array by doing manual offset calculations, but just use a vector.

The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots.

Comments
  • Well, a.Length will give you the length of the string, array.Length will give you the length of the array, you can even call a.ToCharArray(); without any arguments and it will take care of this for you without manually specifying 0,a.Length. What's the issue?
  • Is your question how to find the index of into2ndarray that you need?
  • ya the question is how do i save the result from the case statement into the 2nd array accordingly. thanks for ur response
  • Have a variable will all the char in the right index var alphabet = "abcdefghijklmonp.." and use index of +1 to get your number
  • @mortb: I wanted to demonstrate the principle (quering with a help of Linq), that's why I've preserved the logic (branching)
  • @Dimitry: Fair enough
  • I guess it depends on what you are used to :) This solution is least code, and little code is often easier to maintain. The question does not give us much detail about the requirements, e.g. are there any other letters than A B C etc.
  • So for not required letters you are giving an unrequired result which could be wrong
  • To implement the behavior of OP's code: a.Where( c => c >= 'A' && c <= 'C').Select(c => (int)c -'A' + 1).ToArray();