【问题标题】:Determine end point of a sub string by the character type通过字符类型确定子字符串的结束点
【发布时间】:2018-02-04 08:05:52
【问题描述】:

抱歉,我很难为这篇文章找到合适的标题。如果标题不清楚,请致歉。

我有很多字符串遵循这样的格式

"Application has been dispatched to the client 5  business day(s) ago. Signed application has not been received"

我想将其子串到数字 5 。

所以结果是

 "Application has been dispatched to the client"

但是,我并不总是知道数值前有多少个字符

有些字符串有不同的消息,但结构相似。总有一个数字。

另一个例子

"Client signed the application 13 day(s) ago."

现在在这个中,我想得到以下输出

"Client signed the application"

基本上,我需要一种方法来获取直到数值的所有内容。

我该怎么做?

希望这很清楚,并在此先感谢!

干杯!

【问题讨论】:

标签: c#


【解决方案1】:

听起来你需要一些正则表达式。由于您想要直到数字,这应该可以工作:

var regex = new Regex(@" \d+");
var result = input.Substring(0, regex.Match(input).Index));

(假设 input 是您的字符串)。这将从头开始直到第一个数字,不包括空格。

请注意,如果字符串没有数字,则结果将为空白。如果您希望它在该实例中返回整个字符串,您可以使用if 语句来测试匹配索引是否为零。

【讨论】:

    【解决方案2】:
    string result = Regex.Match(str, @"\D*").Value;
    

    \D 匹配任何非数字字符,* 匹配它 0 次或更多次。

    或者更短一点:

    string result = Regex.Split(str, @"\d")[0];
    

    【讨论】:

      【解决方案3】:

      我喜欢函数式编程,所以我想先在 F# 中解决这个问题。这是我想出的:

      let findNumber (s : string) =
          let rec loop i =
              if i >= s.Length then -1
              elif Core.char.IsDigit s.[i] then i
              else loop (i + 1)
          loop 0
      
      let truncateAtNumber s =
          match findNumber s with
          | -1 -> s
          | p -> (s.Substring (0, p)).Trim ()
      

      短而干净。然而,令我惊讶的是 C# 翻译实际上更短(编辑: 现在更短了):

      static string TruncateAtNumber(this string s)
      {
          for (int i = 0; i < s.Length; i++)
              if (char.IsDigit(s[i]))
                  return s.Substring(0, i).Trim();
          return s;
      }
      

      【讨论】:

      • 非常感谢您的贡献。我选择 Regex 是因为它的紧凑性。但你的方法也很有效。
      【解决方案4】:

      老实说,你可以使用 split() 字符串将字符串值转换为数组

      例如:

      var str = "Client signed the application 13 day(s) ago"; 
      var res = str.Split(' '); // split when space found
      Console.WriteLine(res[0]); // output value when array index at 0
      

      所以,输出应该是:

      Client 
      

      之后你只需循环数组中的数据,当找到可以转换为整数的字符串数据时,必须停止循环

              int number, index = 0;
      
              bool result = false; 
      
              while (result == false)
              {
                  Console.WriteLine(res[index]);
                  index++;
                  result = Int32.TryParse(res[index], out number);
              }
      

      最后输出应该是

      Client 
      signed 
      the 
      application
      

      希望我的回答能帮到你

      【讨论】:

      • 非常感谢您的贡献!由于其紧凑的性质,我不得不选择另一个答案。但感谢您的努力!
      猜你喜欢
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 2022-11-16
      • 2015-08-03
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多