1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
James Morrish
  • 455
  • 6
  • 24
  • 8
    Use [`LastIndexOf(':')`](https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof?view=netframework-4.7.2#System_String_LastIndexOf_System_Char_) followed by `Substring()`s – maccettura Oct 29 '18 at 14:58
  • Just determine the 2nd index https://stackoverflow.com/a/19035944/1315444 – fubo Oct 29 '18 at 15:15

3 Answers3

3

You can use LastIndexOf() and some subsequent Substring() calls:

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);

Fiddle here

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 (i.e not finding the : first):

string firstPart = input.Substring(0, 16);
string secondPart = input.Substring(17);
maccettura
  • 10,514
  • 3
  • 28
  • 35
0

you can reverse the string, then call the regular split method asking for a single result, and then reverse back the two results

Leonardo
  • 10,737
  • 10
  • 62
  • 155
0

and with a regex : 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]);        
        }
    }
}
tschmit007
  • 7,559
  • 2
  • 35
  • 43