Take values separated by spaces in C#?

Asked

Viewed 509 times

3

I want to take the values, for example, 79 201 304 and store in one vector each number at one position.

Example :

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);
            Console.Write(resultado);
        }

        return 0;
    }

I’m doing a job for RSA encryption faculty and this giving problem in the decrypting part need to pick up what the user type that will be numbers separated by spaces and store in vector with to decrypt each number.

1 answer

3


Use the String.Split:

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

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

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

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

See working on Ideone.

There are several ways to make this string to integer conversion. You can even turn it into a List<string> and use the Cast<TResult>. Would look like this:

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

There is also a single line solution. It is the same as the top.

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>

Thus it can harm the reading. I would use as in the first example. I put it just to show that you don’t need multiple lines to get the result.

  • i did this with the split but it appears that "cannot implicitly convert type "string[]" into "string""

  • I got to see how Ideone works, see what I did wrong in the answer below

  • input would be txt pq it which will receive the numbers the user will type

  • got it now, I put where it does the conversion to int an int[] and it worked, obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.