ArgumentIndexOutOfBounds异常string.Length [英] ArgumentIndexOutOfBounds Exception string.Length

查看:309
本文介绍了ArgumentIndexOutOfBounds异常string.Length的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我过去几天的一个问题。这个问题非常类似于昨天我问的一个问题,但是当我更新了这个问题时,没有人碰到过,所以我再一次提出一个新的问题。



我正在处理一个需要大文本文件的程序,将其分为两组:a和b,然后读取数据的每一行。一行数据将如下所示:

  5/22/2015 12:15:55 AM |批量8 | 429/529 | 81.10%| BLV-R |加工的VLZYYL ...检查可退还的票价。传统预订。内部票务窗口。最低节省:$ 100.00。实际储蓄:1,780.60美元。发现储蓄:1,780.60美元(31.11%)。备注备案UDID写排队到0TA9 / 208 * 11。排队到0TA9 / 161 * 222。 

我不会解释什么意思。但是这个程序正在研究的关键要素是Savings found:和它旁边的百分比。然而,并不是每一行都有储蓄,实际上大多数行都没有,但其中一些行。下面我有一段代码,将告诉我文件名是什么,文件有多少行,并查看一个组中的每一行,并写出有多少PNRS被处理,有多少PNRS有储蓄,什么所有具有储蓄的PNRS的百分比(百分比四舍五入到3位小数),然后如果百分比为30%或更大,它应该写出具有储蓄发现:的每一行,它将在该行的前面加上一个星号。如果节省30%或更多,节省$ 500或以上,那么它将在该行的前面放置两个星号。下面我有一个例子,总体输出应该是和我迄今为止的代码:

 控制台想法:
文件名称:PNRS
总数:123,123

组:A
总PNRS:123
PNRS带储蓄:23
%带储蓄: 10%

* 5/21/2015 11:55:56 PM |批量6 | 386/767 | 50.33%| CH2M-R |加工NXRMN5 ...检查可退还和不可退还的票价。传统预订。内部票务窗口。最低节省:$ 131.00。实际节省:$ 257.18。发现储蓄:$ 257.18(11.55%)。以前发现储蓄。
2015-234wefsaf LINE GOES HERE ** 2015 LINES
组:B同一格式作为组A

我一直在努力的代码:

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;
使用System.IO;
使用System.Linq;
命名空间DanProject
{
class Program_Origional
{
static void Main(string [] args)
{
//以下系列代码是phase1
try
{


string path = @c:\users\povermyer\documents\visual studio 2013 \Projects\\ \\DanProject\PNRS\PNRS.log;

if(!File.Exists(path))
{

//Console.WriteLine(\"File not Found);
抛出新的FileNotFoundException();
}
else
{


string [] lines = System.IO.File.ReadAllLines(path);
var count = File.ReadLines(path).Count();
列表< string> a = lines.Take(7678).ToList();
列表< string> s = lines.Skip(7678).Take(5292).ToList();


Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(path));
Console.WriteLine(lines.Count());


if(a.Any(item => item.Contains(Savings found))
{
Console.WriteLine(\\\
Group一个);
var aPNRSThatWereProcessed = a.Count(line => line.Contains(Processed));

Console.WriteLine(在)中处理了+ aPNRSThatWereProcessed +PNRS。


//代码查找储蓄

int aPNRSWhereSavingsWereFound = a.Count(line => line.Contains(Savings found:)) ;
Console.WriteLine(在一个,有+ aPNRSWhereSavingsWereFound +PNRS有节省);

//找到一个
十进制百分比的代码aPercentage =((decimal)aPNRSWhereSavingsWereFound / aPNRSThatWereProcessed * 100);
decimal result1 = Math.Round(aPercentage,3);
Console.WriteLine(节省的PNRS的百分比是+ result1 +%);

string find =储蓄找到:;
foreach(var line in a.Where(w => w.Contains(find)))
{
var subStr = line.Substring(0,line.IndexOf(find)+ find.Length);
var startIndex = subStr.IndexOf('(');
var endIndex = subStr.IndexOf(')');

var savings = double.Parse(subStr.Substring(2,startIndex - 1).Trim());
var percent = double.Parse(subStr.Substring(startIndex + 1,endIndex - startIndex - 2).Trim());

Console.WriteLine({0} {1} {2},(percent> = 30)?*:string.Empty,

= 30&& Saving> = 500)?*:string.Empty,
line);
}
}








}
}

catch(Exception ex)
{

Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadKey();
}


}
}

}

我的问题在于foreach循环。以上所有foreach循环都是完美的,然后当我编译这个,我得到这个确切的错误信息:
System.ArgumentOutOfRangeException:Length不能小于零。参数名称:System.String.Substring(Int32,startIndex,Int32,length)的长度

(我正在使用的文本文件的真长文件名):第66行



正如我所看到的那样,问题在于.Length语句,但是当我尝试用()修复它时,VS对我大声说,我不能这样做。它表示不可调用的成员string.Length不能像方法一样使用。



现在我已经具体了,尽可能详细,请帮忙我在弄清楚如何摆脱这个问题,让这个控制台应用程序滚动!

解决方案

然后@ steve16351告诉你有什么问题。



你正在做 var subStr = line.Substring(0,line.IndexOf(find)+ find.Length);



这将返回'找到储蓄'



你想要的东西像

  var subStr = line.Substring(line.IndexOf(find)+ find.Length); 

哪些会在找到储蓄后给你所有的东西


$ b $告诉你,这将是一个Doh时刻。 :)


Below is a problem that I have been having the past couple of days. This question is very similar to one I asked yesterday, but when I updated the question no one touched it so I am asking it again in a new question.

I am working on a program that takes a large text file, splits it into 2 groups: a and b, and then reads each line of the data. A line of data will look like this:

5/22/2015 12:15:55 AM | Batch 8|429/529|81.10 %|BLV-R|Processed VLZYYL...Checking refundable fares. Traditional Booking. Inside ticketing window. Minimum Savings Required: $100.00. Actual Savings: $1,780.60. Savings found: $1,780.60 (31.11 %). Remark written. UDID written. Queued to 0TA9/208*11. Queued to 0TA9/161*222.

I am not going to explain what everything means. But the key elements that this program is looking at is "Savings found:" and the percent that is next to it. Not every line however has savings, actually most of the lines do not, but some of them do. Below I have a piece of code that will Tell me what the file name is, how many lines the file has, and look at every line in the a group and write out how many PNRS were processed, how many PNRS have savings, what the percent of all the PNRS that had savings(Percent rounded to 3 decimals) and then it is supposed to write out every line that has "Savings found:" if the percent is 30% or greater, it will place an asterisk infront of the line. If it has 30% or greater savings and has $500 or more in savings, then it will place two asterisks in the front of that line. Below I have an example of what the overall output should be and the code that I have thus far:

Console Idea:
FIle Name: PNRS
Total Lines: 123,123

Group: A
Total PNRS: 123
PNRS With Savings: 23
% With Savings: 10%

* 5/21/2015 11:55:56 PM | Batch 6|386/767|50.33 %|CH2M-R|Processed          NXRMN5...Checking refundable and non-refundable fares. Traditional Booking. Inside ticketing window. Minimum Savings Required: $131.00. Actual Savings: $257.18. Savings found: $257.18 (11.55 %). Savings were previously found.
2015-234wefsaf LINE GOES HERE** 2015    LINES 
Group: B SAME FORMAT AS GROUP A

Code that I have been working on:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
namespace DanProject
{
class Program_Origional
{
    static void Main(string[] args)
    {
        //the following series of code is phase1
            try
        {


            string path = @"c:\users\povermyer\documents\visual studio 2013\Projects\DanProject\PNRS\PNRS.log";

            if (!File.Exists(path))
            {

                //Console.WriteLine("File Not Found");
                throw new FileNotFoundException();
            }
            else
            {


                string[] lines = System.IO.File.ReadAllLines(path);
                var count = File.ReadLines(path).Count();
                List<string> a = lines.Take(7678).ToList();
                List<string> s = lines.Skip(7678).Take(5292).ToList();


                Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(path));
                Console.WriteLine(lines.Count());


                if (a.Any(item => item.Contains("Savings found")))
                {
                    Console.WriteLine("\nGroup a\n");
                    var aPNRSThatWereProcessed = a.Count(line => line.Contains("Processed"));

                    Console.WriteLine("There were " + aPNRSThatWereProcessed + " PNRS that were processed in a");


                    //code to find number of savings

                    int aPNRSWhereSavingsWereFound = a.Count(line => line.Contains("Savings found:"));
                    Console.WriteLine("In a, there were " + aPNRSWhereSavingsWereFound + " PNRS that had savings");

                    //code to find percentage for a
                    decimal aPercentage = ((decimal)aPNRSWhereSavingsWereFound / aPNRSThatWereProcessed *100);
                    decimal result1 = Math.Round(aPercentage, 3);
                    Console.WriteLine("The percentage of PNRS in a that had savings were " + result1 + "%");

                    string find = "Savings found:";
                    foreach (var line in a.Where(w => w.Contains(find)))
                    {
                        var subStr = line.Substring(0, line.IndexOf(find) + find.Length);
                        var startIndex = subStr.IndexOf('(');
                        var endIndex = subStr.IndexOf(')');

                        var savings = double.Parse(subStr.Substring(2, startIndex - 1).Trim());
                        var percent = double.Parse(subStr.Substring(startIndex + 1, endIndex - startIndex - 2).Trim());

                        Console.WriteLine("{0}{1}{2}", (percent >= 30) ? "*" : string.Empty,

                                                       (percent >= 30 && savings >= 500) ? "*" : string.Empty,
                                                        line);
                    }
                }








            }
        }

        catch (Exception ex)
        {

            Console.WriteLine(ex.ToString());
        }
        finally
        {
            Console.ReadKey();
        }


    }
}

}

My problem lies within the the foreach loop. Everything above that foreach loop is working perfect, and then when I compile this, I am getting this exact error message: System.ArgumentOutOfRangeException: Length cannot be less than zero. Parameter name: length at System.String.Substring(Int32, startIndex, Int32, length) at (Really long file name for the text file I am working with): line 66

As I can see, the problem is with the .Length statement, however when I try to fix it with the (), VS yells at me and says that I can't do it. It says "Non-invocable member 'string.Length' cannot be used like a method".

Now that I have been as specific, as detailed as possible, please help me in figuring out how I can get rid of this problem and get this console application rolling!

解决方案

Then @steve16351 told you what the problem was.

You are doing var subStr = line.Substring(0, line.IndexOf(find) + find.Length);

which will return 'Savings found'

you want something like

var subStr = line.Substring(line.IndexOf(find) + find.Length);

Which will give you everything after 'Savings found'

Told you it would be a Doh moment. :)

这篇关于ArgumentIndexOutOfBounds异常string.Length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆