【问题标题】:Read through a stream reader and use some text from line通过流阅读器阅读并使用行中的一些文本
【发布时间】:2014-02-25 14:55:42
【问题描述】:

使用 streamReader 读取文件。
如果该行以1 开头,我想使用该行。
该行将显示为:1,103,1,4454:HH

所以我想在第一个 , 之后但在第二个之前获取号码。所以我需要103 并将其分配给ProductId:

int ProductID;

using (StreamReader sr = new StreamReader(fakeFileToProcess))
{
    while (!sr.EndOfStream)
    {
        string line = sr.ReadLine();

        if (line.StartsWith("1,"))
        {
            //so line will be 1,103,1,44543:HH
            //How do I capture the '103'...something like:
            //ProductID = line.read between "1," & ","(next comma)

        }

        if (line.StartsWith("25"))
        {
            continue;
        }
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc-3 stream inputstream


    【解决方案1】:

    你可以使用String.Split()函数来实现:

    来自 MSDN:String.Split()

    返回一个字符串数组,其中包含该字符串中的子字符串 由指定字符串数组的元素分隔。一个 参数指定是否返回空数组元素。

    试试这个:

    string num = line.Split(',')[1].Trim();
    if(int.TryParse(str,out ProductID)
    {
       //success now ProductID contains int value (103)
    }
    

    完整代码:

    int ProductID;    
    using (StreamReader sr = new StreamReader(fakeFileToProcess))
    {
        while (!sr.EndOfStream)
        {
            string line = sr.ReadLine();
    
            if (line.StartsWith("1,"))
            {
                string num = line.Split(',')[1].Trim();
                if(int.TryParse(str,out ProductID)
                {
                    //parsing is successful, now ProductID contains int value (103)
                }    
            }
    
            if (line.StartsWith("25"))
            {
                continue;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      当你有一个非常清晰的分隔数据时使用string.IndexOf
      IndexOf 比拆分字符串要好,因为你不需要创建字符串数组

         if (line.StartsWith("1,"))
         {
             // search the second comma after  the first one....
             int pos = line.IndexOf(',', 2);
      
             // for simplicity, do not check if you really have found a second comma....
             string id = line.Substring(2, pos - 2);
      
             // Try to convert whatever is between the first comma and the second one..
             if(Int32.TryParse(id, out productID))
                 Console.WriteLine("Got it:" + productID.ToString());
      
         }
      

      【讨论】:

        【解决方案3】:

        您可以使用string.Split() 方法来实现您想要的。 要转换为int,请使用int.Parse() 方法。

        因此您可以执行以下操作:

        List<string> items = line.Split(',');
        ProductID = int.Parse(items[1]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多