Get values separated by spaces in C #?

Posted on

Question :

I want to get the values, for example, 79 201 304 and store in a vector each number in a position.


int array[0] = 79;
int array[1] = 201;
int array[2] = 304;
public static int Descriptografa(string txt, int p, int q, int d, int e)
        string[] aux;
        int[] descrypt ;

        int phi, n, res = 0,i;
        string resultado;

        n = p * q;
        phi = (p - 1) * (q - 1);
        d = ((phi * 2) + 1) / e; // d*e ≡ 1 mod (φ n)

        for (i = 0; i < txt.Length; i++)
            aux = txt.Split(' ');
            descrypt[] = Array.ConvertAll(aux, str => int.Parse(str));

            BigInteger big = BigInteger.Pow(descrypt[i], d) % n;
            res = (int)big;
            resultado = char.ConvertFromUtf32(res);

        return 0;

I am doing a job for RSA encryption college and it is giving problem in the part of decrypt I need to get what the user type that will be numbers separated by spaces and store in vector with to decrypt each number.


Answer :

Use String.Split :

var input = "10 15 20";
string[] output = input.Split(' '); // o separador nesse caso é o espaço

Then you get a vector of strings. If what you want are integers, convert the array items to integers. Make sure they are even integers, otherwise the conversion will fail, obviously.

An example of the conversion using Array.ConvertAll<TInput, TOutput> .

int[] outputInt = Array.ConvertAll(output, str => int.Parse(str));

See working at Ideone .

There are several ways to do this conversion from string to integer. It can even turn into a List<string> and use Cast<TResult> . It would look like this:

IEnumerable<int> outputInt = output.ToList().Cast<int>();

It also has the one line solution only. It’s the same as above.

Array.ConvertAll("10 15 20".Split(' '), str => int.Parse(str)); // com Array.ConvertAll<TInput, TOutput>
"10 15 20".Split(' ').ToList().Cast<int>(); // e com Cast<TResult>

This can be detrimental to reading. I would use as in the first example. I put it just to show you do not need multiple lines to get the result.


Leave a Reply

Your email address will not be published. Required fields are marked *