Best way to split string by last occurrence of character?

C#StringSplit

C# Problem Overview


Let's say I need to split string like this:

Input string: "My. name. is Bond._James Bond!" Output 2 strings:

  1. "My. name. is Bond"
  2. "_James Bond!"

I tried this:

int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);

Can someone propose more elegant way?

C# Solutions


Solution 1 - C#

Updated Answer (for C# 8 and above)

C# 8 introduced a new feature called ranges and indices, which offer a more concise syntax for working with strings.

string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');

if (idx != -1)
{
    Console.WriteLine(s[..idx]); // "My. name. is Bond"
    Console.WriteLine(s[(idx + 1)..]); // "_James Bond!"
}

Original Answer (for C# 7 and below)

This is the original answer that uses the string.Substring(int, int) method. It's still OK to use this method if you prefer.

string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');

if (idx != -1)
{
    Console.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"
    Console.WriteLine(s.Substring(idx + 1)); // "_James Bond!"
}

Solution 2 - C#

You can also use a little bit of LINQ. The first part is a little verbose, but the last part is pretty concise :

string input = "My. name. is Bond._James Bond!";

string[] split = input.Split('.');
string firstPart = string.Join(".", split.Take(split.Length - 1)); //My. name. is Bond
string lastPart = split.Last(); //_James Bond!

Solution 3 - C#

string[] theSplit = inputString.Split('_'); // split at underscore
string firstPart = theSplit[0]; // get the first part
string secondPart = "_" + theSplit[1]; // get the second part and concatenate the underscore to at the front

EDIT: Following from the comments; this only works if you have one instance of the underscore character in your input string.

Solution 4 - C#

  1. Assuming you only want the split character to appear on the second and greater split strings...

  2. Assuming you want to ignore duplicate split characters...

  3. More curly braces... check...

  4. More elegant... maybe...

  5. More fun... Heck yeah!!

    var s = "My. name. is Bond._James Bond!";
    var firstSplit = true;
    var splitChar = '_';
    var splitStrings = s.Split(new[] { splitChar }, StringSplitOptions.RemoveEmptyEntries)
        .Select(x =>
        {
            if (!firstSplit)
            {
                return splitChar + x;
            }
            firstSplit = false;
            return x;
        });
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2706838View Question on Stackoverflow
Solution 1 - C#Phil KView Answer on Stackoverflow
Solution 2 - C#Pierre-Luc PineaultView Answer on Stackoverflow
Solution 3 - C#rexView Answer on Stackoverflow
Solution 4 - C#KevinView Answer on Stackoverflow