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?

asked May 16, 2022 at 9:26
\$\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)..]);
answered May 16, 2022 at 10:10
\$\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\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented May 16, 2022 at 16:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.