C# – Split String in One Line and Get the First SubString

Imagine, that you are given a string in C# with some separator in it, and you need to split it and refer to the first or the second part of the splitted string.

E.g., you are having *AAAaa*SEPARATOR*zzZZZ* and with one line, you should split it and refer to *AAAaa*  and with the other *zzZZZ* . The one line is really important here, thus we are not even allowed to refer to SEPARATOR as a variable.

So, with other ways, we have two ways to get substrings with one liners, without additional variables nor loops, LINQ or anything fancy:

using System;

class StartUp
{
    static void Main()
    {
        string sample = "*AAAaa*SEPARATOR*zzZZZ*";
        string first = sample.Substring(0, sample.IndexOf("SEPARATOR"));
        string second = sample.Substring(sample.IndexOf("SEPARATOR") + "SEPARATOR".Length);
        Console.WriteLine("{0} - {1}",first,second);

        sample = "111SEPARATOR222SEPARATOR333SEPARATOR333SEPARATOR999";
        first = sample.Split("SEPARATOR".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0];
        second = sample.Split("SEPARATOR".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1];
        string lastOne = sample.Split("SEPARATOR".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
            [sample.Split("SEPARATOR".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length-1];
        Console.WriteLine("{0} - {1} - {2}", first, second, lastOne);
    }
}

If the code above looks a bit strange to you and you do not know who the hell would need 1-liners for something like this (after all, the best case scenario is to write a nice function for this), then you are somehow lucky.

Anyway, for anyone else, who is fighting with 1-liners because of a ******  that uses C#, VB.NET, XAML, CSS and even some HTML in there, this is what the code above produces:

And if you ever have to use something as ****** as the lastOne, do not hate yourself, it is not your fault, it is the IDE…