【问题标题】:Turning a String[] into an int[] and then the int[] into separate variables (x, y, z)将 String[] 转换为 int[],然后将 int[] 转换为单独的变量 (x, y, z)
【发布时间】:2016-04-14 15:54:55
【问题描述】:

我是编程新手,已决定逐步学习 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;
        }
    }
}

【问题讨论】:

  • 为什么不直接从x = Int32.Parse(newArray[0])这样的字符串数组中赋值xyz
  • 最好先阅读几页您想学习的语言教程。我敢打赌它会说一些关于重复操作的事情......
  • @ThorstenDittmar 我不太清楚为什么我不直接分配它并在那里解析。好问题。
  • @AlexeiLevenkov 我已经阅读过重复操作,并且在这段代码中还没有包含它们。在让它多次做我想做的事情之前,我一直专注于让它先做我想做的事情。

标签: c# arrays string methods integer


【解决方案1】:

我看到的唯一问题是int.Parse() 如果不喜欢输入,则会引发异常。此外,您永远不会检查该行是否实际包含 3 个值。我不喜欢将 out 用于三个值,因为它们可以组合成一个 struct Point { int x,y,z; } 并从函数中返回。

所以我建议使用int.TryParse() 为解析创建一个Extension Method,并返回一个与字符串数组大小相同的整数数组。

{
    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.TryParse()这样的语法对我来说是未知的,我现在会调查它。
【解决方案2】:

如果您确信文本文件包含一行,其中包含由一个或多个空格分隔的三个数字,那么此代码有效:

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

【讨论】:

    【解决方案3】:

    在您的情况下,不要使用StreamReader 尝试File.ReadAllLines From MSDN

    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 来保存值并创建ListArray

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 2016-02-08
      • 2016-03-18
      相关资源
      最近更新 更多