# Split string by last occurence of character within a range

So I would like to split a string in two by the last space within the first 40 characters, the best solution I could think of:

public static void Main(string[] sargs)
{
var address = "...Are included in two of the " +
"substrings. If you want to exclude the " +
"period characters, you can add the period...";

var splitIndex = address.LastIndexOf(' ', 40);

}


Is there a better, faster or more elegant way of doing it?

You can use the index and range operators instead of SubString calls

var address = "...Are included in two of the " +
"substrings. If you want to exclude the " +
"period characters, you can add the period...";

var splitIndex = address.LastIndexOf(' ', 40);


• @anastaciu Well in case of C# 7 you can't really do too much differently. Maybe you can make the address2 definition a bit more concise: address.Replace(address1, "") May 16 at 11:13
• don't forget to cover null and index exceptions. also, maybe using a method (or extension method) that returns a tuple (string Address1, string Address2) might give more readability to the context.
• @iSR5 Yepp, that's correct. I've assumed the question is more about the usage of LastIndexOf and Substring. But yeah splitting computation from presentation is essentail. May 16 at 13:21