Best way to split string by last occurrence of character?

c#, split, string

Solution

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!"
}

Problem

Let's say I need to split string like this: Input string: "My. name. is Bond._James Bond!" Output 2 strings: - "My. name. is Bond" - "_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?

Original source