首页 > 解决方案 > 如何在 C# 中将字符串转换为整数数组

问题描述

我是 C# 新手。我正在尝试解决一个必须找到非耦合整数的问题。我正在使用在线编译器。

给定输入

1, 2, 3, 1, 2

该程序应输出:

3

我创建了以下程序 -

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

    
    }
}

我无法将字符串转换1, 2, 3, 1, 2为整数数组。

我有以下错误

 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)

当我添加System.linq时,它给了我

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

标签: c#linqxor

解决方案


试试这个,

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

}

或者通过使用Linq,只需替换如下,你应该需要使用System.Linq命名空间。

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

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


推荐阅读