将String[]转换为int[],然后将int[]转换为单独的变量(x,y,z)
本文关键字:int 转换 然后 String 单独 变量 | 更新日期: 2023-09-27 18:29:36
我是编程新手,决定采取步骤学习C#,在学习某些教程、书籍和其他指南时,我遇到了StreamReader命令。
由于我的学习方式是玩我觉得有趣的新命令,我决定在命令中摸索,看看我能做什么
这就引出了一个问题,我在这里有我的代码,它可以做我想做的事情。
它从文件中提取一行,将其转换为字符串数组,然后将其转换成int数组,然后我将数组的每个部分分类到一个变量中,以便在代码的主要部分中使用。
我想知道的是,有没有一种更清洁的方法来做到这一点?当我包括从文件中提取的第二行、口渴等行时,我能使用Turner方法(?)重复这个过程吗?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StreamReaderToIntArray
{
class Program
{
static void Main(string[] args)
{
int x = 0;
int y = 0;
int z = 0;
string[] stringSeperators = new string[] { " " };
StreamReader myReader = new StreamReader("Values.txt");
string line = myReader.ReadLine();
var myArray = line.Split(stringSeperators, StringSplitOptions.RemoveEmptyEntries);
myReader.Close();
Turner(myArray, out x, out y, out z);
}
static private int Turner(string[] newArray, out int x, out int y, out int z)
{
int[] cArray = newArray.Select(int.Parse).ToArray();
x = cArray[0];
y = cArray[1];
z = cArray[2];
return x;
}
}
}
我看到的唯一问题是,如果int.Parse()
不喜欢输入,它会抛出异常。此外,您永远不会检查该行是否真的包含3个值。我不喜欢对三个值使用out
,因为它们可以组合成一个struct Point { int x,y,z; }
并从函数中返回。
因此,我建议使用int.TryParse()
为解析创建一个扩展方法,并返回一个与字符串数组大小相同的整数数组。
{
string line = myReader.ReadLine();
var point = Point.Parse(line);
}
public struct Point
{
readonly int x, y, z; // Always make struct immutable
public Point(int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public int X { get { return x; } }
public int Y { get { return y; } }
public int Z { get { return z; } }
public static Point Parse(string line)
{
var parts = line.Split(stringSeperators, StringSplitOptions.RemoveEmptyEntries);
var array = parts.Select( (s)=> s.ParseInt() ).ToArray();
if(array.Length>=3)
{
return new Point(array[0],array[1],array[2]);
}
throw new IndexOutOfRangeException();
}
}
// Example extensions for parsing strings
public static class Extensions
{
public int ParseInt(this string value)
{
int x = 0;
int.TryParse(value, out x);
return x;
}
public float ParseFloat(this string value)
{
float x = 0;
float.TryParse(value, out x);
return x;
}
}
如果您确信文本文件包含一行,其中三个数字由一个或多个空格分隔,则此代码有效:
int[] values =
File
.ReadAllText("Values.txt")
.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int x = values[0];
int y = values[1];
int z = values[2];
如果不使用StreamReader
,请尝试MSDN 中的File.ReadAllLines
static void Main(string[] args)
{
int x = 0;
int y = 0;
int z = 0;
string[] stringSeperators = new string[] { " " };
string[] lines = File.ReadAllLines("Values.txt");
foreach(string line in lines)
{
string[] myArray = line.Split(stringSeperators,
StringSplitOptions.RemoveEmptyEntries);
Turner(myArray, out x, out y, out z);
}
}
但采用这种方法,变量x, y, z
将只保留最后一行的值
考虑使用@ja72的struct
来保存值,并创建值
List
或Array