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