【问题标题】:how to get values from text using .IndexOf and .Substring in c#?如何在 c# 中使用 .IndexOf 和 .Substring 从文本中获取值?
【发布时间】:2015-01-27 13:43:44
【问题描述】:

我需要对字符串变量中的几个值进行求和,

这是我的变量:

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"

在这种情况下,我需要取出 (7,-7,7,2) 的值吗?结果得到 9。

我试着这样做:

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

            }

但它不起作用,因为我在 y 变量中不断得到“V”。

任何帮助将不胜感激

【问题讨论】:

  • 使用 string.Split 和 Linq 表达式来总结你的行的第二列。
  • 为什么不想要最后一行的 2?
  • 我想要它,但我忘记在问题中添加它......对不起
  • 该字符串中是否有换行符或者它只是一行文本?
  • 有趣,请检查你的数学。

标签: c# .net string indexing


【解决方案1】:

如果那些逗号和换行符总是在那里,这应该可以工作:

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

因此,您将发票分成几行并丢弃前两行(“Invoice Details”和“INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE”)。然后你用逗号分割每一行,取第三个值——第一个是日期,第二个是“New Corpbundle 7”部分,第三个是你的值。您将该值解析为 int,然后对所有内容求和。

您可能会发现您需要正确过滤掉这些行,而不是仅仅假设您可以跳过前两个并使用其余的行,但这应该可以帮助您开始。

【讨论】:

  • 没有澄清单行或多行问题,我认为这个答案是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2011-08-18
  • 2021-01-09
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
相关资源
最近更新 更多