Search code examples
c#linqxor

How to Convert a String into Integer Array in C#


I am new to C#. I am trying to solve a problem in which I have to find uncoupled integers. I am using an online compiler.

Given the input

1, 2, 3, 1, 2

The program should output:

3

I created the following program -

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        int[] num;
        int accum=0;
        int j=0;
        string input = Console.ReadLine();
        input = input.Replace(",","");
        
            
        num = input.Select(int.Parse).ToArray(); 
             

        for (int i = 0; i < num.length; i++)
           accum ^= num[i];
           Console.WriteLine(accum);

    
    }
}

I am having trouble in converting string 1, 2, 3, 1, 2 into integer array.

I am having following errors

 error CS1061: Type `string' does not contain a definition for `Select' and no extension method `Select' of type `string' could be found. Are you missing `System.Reactive.Linq' or `System.Linq' using directive?
/usr/lib/mono/4.7.2-api/mscorlib.dll (Location of the symbol related to previous error)
Solution.cs(18,29): error CS1061: Type `int[]' does not contain a definition for `length' and no extension method `length' of type `int[]' could be found. Are you missing an assembly reference?
/usr/lib/mono/4.7.2-api/mscorlib.dll (Location of the symbol related to previous error)

When I added System.linq, it gave me

error CS0234: The type or namespace name `linq' does not exist in the namespace `System'. Are you missing an assembly reference?


Solution

  • Try this,

    static void Main(string[] args)
    {
        int[] num;
        int accum = 0;
        string input = Console.ReadLine();
    
        num = Array.ConvertAll(input.Split(','), int.Parse);
    
        for (int i = 0; i < num.Length; i++)
            accum ^= num[i];
        Console.WriteLine(accum);
    
    }
    

    Or by using Linq, just replace as follows, and you should need to use System.Linq namespace.

    num = input.Split(',').Select(int.Parse).ToArray();
    

    .NetFiddle : https://dotnetfiddle.net/bahpg9