Split string by last occurence of character within a range

Posted on

Problem

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

    var address1 = address.Substring(0, splitIndex);
    var address2 = address.Substring(splitIndex + 1, address.Length - splitIndex - 1);
        
    Console.WriteLine(address1);
    Console.WriteLine(address2);

}

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

Solution

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

Console.WriteLine(address[..splitIndex]);    
Console.WriteLine(address[(splitIndex+1)..]);

Leave a Reply

Your email address will not be published. Required fields are marked *