1

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.

4
  • 1
    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? Commented Feb 10, 2020 at 8:40
  • Is your question how to find the index of into2ndarray that you need? Commented Feb 10, 2020 at 8:42
  • ya the question is how do i save the result from the case statement into the 2nd array accordingly. thanks for ur response Commented Feb 10, 2020 at 8:44
  • Have a variable will all the char in the right index var alphabet = "abcdefghijklmonp.." and use index of +1 to get your number Commented Feb 10, 2020 at 8:46

6 Answers 6

8

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     
Sign up to request clarification or add additional context in comments.

2 Comments

@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
3

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;
    }
}

Comments

2

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();

Comments

1

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;
  }

}

Comments

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

3 Comments

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();
1

It is possible to use Dictionary<TKey, TValue>:

Dictionary<char, int> keySizes = new Dictionary<char, int> {
    { 'A', 2 },
    { 'B', 2 },
    { 'C', 2 }
};

An example:

public static int[] ConvertStringToArray()
{
    string str = "ABCA";
    char[] array;
    array = str.ToCharArray(0, str.Count());
    int[] into2ndarray = new int[] { };

    Dictionary<char, int> keySizes = new Dictionary<char, int> {
         { 'A', 2 },
         { 'B', 2 },
         { 'C', 2 }
    };
    int arraySize;
    foreach (char c in array)
    {
        if (keySizes.TryGetValue(c, out arraySize))
        {
            into2ndarray = new int[arraySize];
            break;
        }   
    }
    return into2ndarray;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.