\$\begingroup\$
\$\endgroup\$
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?
anastaciuanastaciu
asked May 16, 2022 at 9:26
1 Answer 1
\$\begingroup\$
\$\endgroup\$
5
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
-
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– anastaciu2022年05月16日 10:21:13 +00:00Commented 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\$Peter Csala– Peter Csala2022年05月16日 11:13:19 +00:00Commented 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– iSR52022年05月16日 12:32:36 +00:00Commented 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
andSubstring
. But yeah splitting computation from presentation is essentail. \$\endgroup\$Peter Csala– Peter Csala2022年05月16日 13:21:32 +00:00Commented 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– anastaciu2022年05月16日 16:32:10 +00:00Commented May 16, 2022 at 16:32
lang-cs