Is there a way to change "ABCDEFGHIJKLMNOP
" to "ABCD-EFGH-IJKL-MNOP
" using string.format()
function or perhaps LINQ ?
I am using this statement
Out= String.Format("{0}-{1}", String.Format("{0}-{1}-{2}", In.Substring(0, 4), In.Substring(4, 4), In.Substring(8, 4)), In.Substring(12, 4));
is there a better and clearer way to accomplish this?
You could use string.Format
, but you would still have to use SubString
to get the different parts.
You should probably just use Insert
:
string result = myString.Insert(12, "-").Insert(8, "-").Insert(4, "-");
LINQ is overkill for something like this.
This is really easy to do without LINQ or string.format, so I would suggest using this code instead:
string s = "ABCDEFGHIJKLMNOP";
for( int i = 4; i < s.Length; i += 5){
s = s.Insert(i, "-");
}
This will insert a dash after each 4 characters (i assumed that is what you wanted).
Just for fun, in Linq:
string result = input.Select((c, i) => i > 0 && i % 4 == 0 ? "-" + c : c.ToString())
.Aggregate((s1, s2) => s1 + s2);
Of course, I wouldn't recommand using Linq in this case, as a 'classical' solution would be more efficient AND more readable.
Still, I enjoyed writing this one :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With