简体   繁体   English

如何在C#中使用.IndexOf和.Substring从文本获取值?

[英]how to get values from text using .IndexOf and .Substring in c#?

I need to make a summation for several values out from string variable, 我需要对字符串变量中的多个值求和,

Here is my variable: 这是我的变量:

string strBillHeader =  "Invoice Details
INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,Missed Call ALERT with Offer,2,01/11/2014,30/11/2014"

I need to get out the VALUES which are (7,-7,7,2) in this case? 在这种情况下,我需要找出(7,-7,7,2)的值吗? and to get 9 as a result. 结果是9

I tried to do it this way: 我试图这样做:

             for (int x = 4; x <= countCommas - 3; x += 4)
            {
int firstCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + x);
                    int secondCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + (x + 1));
                    string y = strBillHeader.Substring(firstCommaIndex + 1, 1);
                    chargeAmount = Convert.ToInt32(y);
                    //chargeAmount = Int32.Parse(strBillHeader.Substring(firstCommaIndex, secondCommaIndex - firstCommaIndex));
                    TotalChargeAmount += ChargeAmount;

                //string AstrBillHeader = strBillHeader.Split(',')[0];

            }

but it did not work since I keep getting 'V' in the y variable. 但是它没有用,因为我一直在y变量中获得'V'。

Any help will be appreciated 任何帮助将不胜感激

If those commas and newlines are always there, this should work: 如果这些逗号和换行符始终存在,则应该起作用:

var lines = strBillHeader.Split(Environment.NewLine).Skip(2);
int total = lines.Split(',').Sum(line => Convert.ToInt32(line[2]));

So, you split the invoice into lines and discard the first 2 (" Invoice Details " and " INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE "). 因此,您将发票分成几行,并丢弃了前2个(“ Invoice Details ”和“ INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE ”)。 Then you split each line on the commas, and take the third value - the first is a date, the second is the " New Corpbundle 7 " part, the third is your value. 然后,您在逗号上分割每一行,并获取第三个值-第一个是日期,第二个是“ New Corpbundle 7 ”部分,第三个是您的值。 You parse that value as an int , and sum the whole lot. 您将该值解析为int ,然后将全部加总。

You may find you need to filter out the lines properly, rather than just assuming you can skip the first two and use the rest, but this should get you started. 您可能会发现需要适当地过滤掉行,而不仅仅是假设您可以跳过前两个并使用其余的行,但这应该可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM