在第n个出现的字符

时间:2018-10-29 14:58:14

标签: c# split

我有很多这样的字符串:

29/10/2018 14:50:09402325 671

我想分割这些字符串,使它们像这样:

29/10/2018 14:50

09402325 671

然后将它们添加到数据集中并在以后进行分析。

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

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

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

我该怎么做?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您可以反转字符串,然后调用常规split方法询问单个结果,然后反转两个结果

答案 2 :(得分:0)

并带有正则表达式: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]);        
        }
    }
}
相关问题