[英]Split string on Nth occurrence of char
I have this a lot of strings like this: 我有很多这样的字符串:
29/10/2018 14:50:09402325 671
I want to split these string so they are like this: 我想分割这些字符串,使它们像这样:
29/10/2018 14:50
09402325 671
These will then be added to a data set and analysed later. 然后将它们添加到数据集中,然后进行分析。
The issue I am having is if I use this code: 我遇到的问题是如果我使用以下代码:
string[] words = emaildata.Split(':');
it splits them twice; 它分裂了两次; I only want to split it once on the second occurrence of the :.
我只想在第二次出现时将其拆分一次。
How can I do that? 我怎样才能做到这一点?
You can use LastIndexOf()
and some subsequent Substring()
calls: 您可以使用
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);
However, another thing to ask yourself is if you even need to make it more complicated than it needs to be. 但是,另一个要问自己的问题是,您是否甚至需要使其变得比所需的复杂。 It looks like this data will always be of a the same length until that second
:
instance right? 它看起来像这样的数据将永远是相同的长度,直到第二
:
实例吧? Why not just split at a known index (ie not finding the :
first): 为什么不是一个已知的指数仅为拆分(即没有找到
:
在前):
string firstPart = input.Substring(0, 16);
string secondPart = input.Substring(17);
您可以反转字符串,然后调用常规的split方法询问单个结果,然后反转两个结果
and with a regex : https://dotnetfiddle.net/Nfiwmv 并使用正则表达式: 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]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.