Im still learning in C#, and there is one thing i cant really seem to find the answer to.
If i have a string that looks like this “abcdefg012345”, and i want to make it look like “ab-cde-fg-012345”
i tought of something like this:
string S1 = "abcdefg012345";
string S2 = S1.Insert(2, "-");
string S3 = S2.Insert(6, "-");
string S4 = S3.Insert.....
...
..
Now i was looking if it would be possible to get this al into 1 line somehow, without having to make all those strings.
I assume this would be possible somehow ?
Whether or not you can make this a one-liner (you can), it will always cause multiple strings to be created, due to the immutability of the
Stringin .NETIf you want to do this somewhat efficiently, without creating multiple strings, you could use a
StringBuilder. An extension method could also be useful to make it easier to use.Note that this example initialises
StringBuilderto the correct length up-front, therefore avoiding the need to grow the StringBuilder.Usage:
"abcdefg012345".MultiInsert("-",2,5); // yields "abc-def-g012345"Live example: http://rextester.com/EZPQ89741