Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a comma after each char in c#

Tags:

c#

I need a way to insert a comma after every character in a string. So for example, if i have the string of letters

"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

I need to make it so there is a comma after every letter from A, to Z, I would like to keep the string as it is and not convert it to a char array or something like that. I dont know if thats possible but its just something id like to avoid.

How can i do this? End result should be this:

"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,"

Thanks

like image 939
Joe Avatar asked Aug 05 '11 13:08

Joe


2 Answers

In .Net 4:

str = String.Join<char>(",", str) + ",";

.Net 4.0 adds a String.Join overload that takes an IEnumerable<T>.
This code calls it with String casted to IEnumerable<char>.

I need to explicitly specify the generic type parameter or it will call the params string[] overload (using a single string) instead.

like image 141
SLaks Avatar answered Nov 12 '22 09:11

SLaks


Well you've got to do something to generate the new string. The simplest approach would probably be in .NET 4:

// string.Join won't put the trailing comma
string result = string.Join(",", (IEnumerable<char>) input) + ",";

or

string result = string.Join<char>(",", input) + ",";

Or in .NET 3.5, where the overload we want doesn't exist:

// string.Join won't put the trailing comma
string result = string.Join(",", input.Select(c => c.ToString())
                                      .ToArray()) + ",";

If these aren't efficient enough for you, you could always do it manually:

StringBuilder builder = new StringBuilder(input.Length * 2);
foreach (char c in input)
{
    builder.Append(c);
    builder.Append(',');
}
string result = builder.ToString();
like image 20
Jon Skeet Avatar answered Nov 12 '22 08:11

Jon Skeet