2
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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)..]);
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Nice, wasn't aware of this, I think I have to comply with c# 7.0, I'll have to check, but nice nonetheless... \$\endgroup\$
    – anastaciu
    May 16, 2022 at 10:21
  • \$\begingroup\$ @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, "") \$\endgroup\$ May 16, 2022 at 11:13
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – iSR5
    May 16, 2022 at 12:32
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ May 16, 2022 at 13:21
  • \$\begingroup\$ @iSR5 Thanks for the advice. the index exceptions are covered, this is just a test in fact the code is to split large large strings into smaller ones because of a payload list I need to send via post. I added that code for review if you're interested : codereview.stackexchange.com/q/276598/217541 \$\endgroup\$
    – anastaciu
    May 16, 2022 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.