c# - 如何在 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?
解决方案
试试这个,
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
推荐阅读
- pine-script - 在 Pine Editor 策略中,是否可以编写代码以使条目在条件发生 1 分钟后仍然为真(在 3 分钟 TF 上)?
- amazon-web-services - 如何将 s3 存储桶连接到 AWS amplify?
- r - R中基于多个变量和子组的字符变量的比例
- sql - 如何加快以下审计日志查询
- postgresql-9.6 - 如何在spring mvc中使用带有过滤器的concat命令
- husky - 尝试提交时出现奇怪的错误。[主题为空]
- reactjs - 为什么我添加 backgourd-image 的属性时反应会抛出错误
- ios - 如何使用 UIDocumentPickerViewController 返回的 URL 保存对文件的更改?
- javascript - 如何从数组中的对象中选择一个值
- machine-learning - 使用 MLPRegressor 与 KerasRegressor 获得显着不同的结果