再说一遍,我是一名离散数学家,不是编码员,而是尝试使用 C# 来撰写我正在撰写的论文,并且需要一些帮助。
我有一个代码可以根据用户输入生成一组随机整数,并将它们打印为以逗号分隔的字符串,但需要将它们转换为向量(或 int 数组?)。我不太确定哪个合适,但我在网上找不到太多关于如何在 C# 中使用其中一个的信息。我需要能够对它们应用向量函数,因此每个条目仍然需要可识别并且是整数,但向量需要能够根据用户输入改变大小。
最佳答案
如果您已有逗号分隔的字符串,则可以使用 String.Split()
方法根据逗号将其拆分为数组,然后您可以使用 Int32.Parse()
将每个值转换为适当的整数或Convert.ToInt32()
方法分别:
// The Split() method will yield an array, then the Select() statement
// will map each string value to it's appropriate integer and finally
// the last ToArray() call will make this into an actual array of integers
var output = input.Split(',').Select(n => Int32.Parse(n)).ToArray();
您可以see an example of this in action here 。如果您需要明确忽略可能的空条目和空格,您可以使用以下调整后的示例:
var output = input.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => Int32.Parse(s.Trim()))
.ToArray();
更安全的方法仍然是仅使用可以通过 Int32.TryParse()
正确解析为整数的值。方法如下:
// Split your string, removing any empty entries
var output = strings.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries)
.Select(n => {
// A variable to store your value
int v;
// Attempt to parse it, store an indicator if the parse was
// successful (and store the value in your v parameter)
var success = Int32.TryParse(n, out v);
// Return an object containing your value and if it was successful
return new { Number = v, Successful = success };
})
// Now only select those that were successful
.Where(attempt => attempt.Successful)
// Grab only the numbers for the successful attempts
.Select(attempt => attempt.Number)
// Place this into an array
.ToArray();
关于C# 将生成的数字列表转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803060/