【问题标题】:Split string on Nth occurrence of char在第 N 次出现 char 时拆分字符串
【发布时间】:2019-04-02 13:03:27
【问题描述】:

我有很多这样的字符串:

29/10/2018 14:50:09402325 671

我想把这些字符串拆分成这样:

29/10/2018 14:50

09402325 671

这些将被添加到数据集中并稍后进行分析。

如果我使用此代码,我遇到的问题是:

 string[] words = emaildata.Split(':');

将它们拆分两次;我只想在 :. 的第二次出现时将其拆分一次。

我该怎么做?

【问题讨论】:

标签: c# split


【解决方案1】:

并使用正则表达式:https://dotnetfiddle.net/Nfiwmv

using System;
using System.Text.RegularExpressions;

public class Program  {
    public static void Main() {
        string input = "29/10/2018 14:50:09402325 671";
        Regex rx = new Regex(@"(.*):([^:]+)",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);

        MatchCollection matches = rx.Matches(input);
        if ( matches.Count >= 1 ) {
            var m = matches[0].Groups;
            Console.WriteLine(m[1]);
            Console.WriteLine(m[2]);        
        }
    }
}

【讨论】:

    【解决方案2】:

    您可以使用LastIndexOf() 和一些后续的Substring() 调用:

    string input = "29/10/2018 14:50:09402325 671";
    
    int index = input.LastIndexOf(':');
    
    string firstPart = input.Substring(0, index);
    string secondPart = input.Substring(index + 1);
    

    小提琴here

    但是,要问自己的另一件事是,您是否甚至需要使它变得比需要的更复杂。看起来这些数据的长度总是相同直到第二个: 实例,对吧?为什么不直接在已知索引处拆分(即首先没有找到:):

    string firstPart = input.Substring(0, 16);
    string secondPart = input.Substring(17);
    

    【讨论】:

    • 很好的答案,关于日期时间总是相同长度的非常有效的观点,非常感谢。
    【解决方案3】:

    你可以反转字符串,然后调用常规的 split 方法要求一个结果,然后将两个结果反转回来

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多