Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to separate string using string.format() function or LINQ ?

Tags:

string

c#

linq

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?

like image 563
Rzassar Avatar asked Nov 28 '11 12:11

Rzassar


3 Answers

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.

like image 160
Oded Avatar answered Oct 23 '22 04:10

Oded


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).

like image 9
Øyvind Bråthen Avatar answered Oct 23 '22 03:10

Øyvind Bråthen


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

like image 3
Kevin Gosse Avatar answered Oct 23 '22 03:10

Kevin Gosse