【问题标题】:C# substring in the middle中间的 C# 子字符串
【发布时间】:2012-12-29 13:48:11
【问题描述】:

我有以下数据:

D:\toto\food\Cloture_49000ert1_10_01_2013.pdf
D:\toto\food\Cloture_856589_12_01_2013.pdf
D:\toto\food\Cloture_66rr5254_10_12_2012.pdf

如何提取日期部分? 例如:

D:\toto\food\Cloture_49000ert1_10_01_2013.pdf --> 10_01_2013
D:\toto\food\Cloture_856589_12_01_2013.pdf --> 12_01_2013
D:\toto\food\Cloture_66rr5254_10_12_2012.pdf --> 10_12_2012

我的想法是使用LastIndexOf(".pdf"),然后倒数10个字符。

如何使用子字符串或其他方法解决此问题?

【问题讨论】:

  • 顺便说一下,D:\toto\food\Cloture_49000ert1_10_01_2013.pdf 不是一个有效的字符串。

标签: c# string substring


【解决方案1】:

在这种情况下使用 Substring

从此实例中检索子字符串。子字符串开始于 指定字符位置。

这样试试;

string s = "D:\\toto\\food\\Cloture_490001_10_01_2013.pdf";
string newstring = s.Substring(s.Length - 14, 10);
Console.WriteLine(newstring);

这是一个DEMO

【讨论】:

    【解决方案2】:

    你不需要找到.pdf的索引

    path.Substring(path.Length - 14, 10)
    

    【讨论】:

    • 我假设所有文件名都以 dateString.pdf 结尾
    【解决方案3】:

    我会用正则表达式来做到这一点。

    ^[\w:\\]+cloture_(\d+)_([\d_]+).pdf$
    

    将匹配第二组中的日期。

    【讨论】:

      【解决方案4】:

      如果文件名始终采用该格式,您可以执行如下粗略的操作:

      string filename = @"D:\toto\food\Cloture_490001_10_01_2013.pdf";
      
      string date = filename.Substring(filename.Length - 14, 10);
      

      这将从10_01_2013.pdf 得到一个子字符串,它有14 个字符长,但只取第一个10 字符,剩下10_01_2013

      但是,如果文件名采用不同的格式并且日期可能出现在名称中的任何位置,您可能需要考虑使用正则表达式之类的方法来匹配 ##_##_#### 并将其提取出来。

      【讨论】:

        【解决方案5】:

        试试这个方法:

        string dateString = textString.Substring(textString.Length-14, 10);
        

        也可以在这里查看:Extract only right most n letters from a string

        【讨论】:

          【解决方案6】:

          如果你想使用 LastIndexOf 那么

          string str = @"D:\toto\food\Cloture_490001_10_01_2013.pdf";
          string temp = str.Substring(str.LastIndexOf(".pdf") - 10, 10);
          

          你可以像这样解析它

          DateTime dt;
          if(DateTime.TryParseExact(temp, "MM_dd_yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
          {
              //valid 
          }
          else
          {
              //invalid
          }
          

          【讨论】:

            【解决方案7】:

            我会同意你使用LastIndexOf“.pdf”的想法,然后倒数。或者使用Path.GetFileNameWithoutExtension 方法只获取名称,然后取最后10 个字符。

            如果文件名的路径发生变化(它可能会),这些方法都将继续工作,并且不依赖幻数(除了定义我们感兴趣的子字符串长度的那个)来查找字符串中的正确位置。

            【讨论】:

            • 如果你仔细想想,它仍然依赖于幻数/定位。不过,Substring 解决方案并不依赖于文件名的长度相同。
            • @RudiVisser - 嗯,只有所需的子字符串长度的幻数。
            • 是的,但它和Substring 一样,除了我们也假设一个 3 字符扩展名:)
            猜你喜欢
            • 2015-06-28
            • 2013-12-11
            • 1970-01-01
            • 2015-08-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多