Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Trim the leading comma in my string

Tags:

string

c#

.net

trim

I have a string that is like below.

,liger, unicorn, snipe

in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?

Thanks.


There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.

like image 603
Keng Avatar asked Sep 16 '08 15:09

Keng


4 Answers

string s = ",liger, unicorn, snipe";
s.TrimStart(',');
like image 177
DevelopingChris Avatar answered Sep 23 '22 19:09

DevelopingChris


string sample = ",liger, unicorn, snipe";
sample = sample.TrimStart(','); // to remove just the first comma

Or perhaps:

sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma
like image 36
RickL Avatar answered Sep 24 '22 19:09

RickL


.net strings can do Trim() and TrimStart(). Because it takes params, you can write:

",liger, unicorn, snipe".TrimStart(',')

and if you have more than one character to trim, you can write:

",liger, unicorn, snipe".TrimStart(",; ".ToCharArray())
like image 43
Jay Bazuzi Avatar answered Sep 21 '22 19:09

Jay Bazuzi


here is an easy way to not produce the leading comma to begin with:

string[] animals = { "liger", "unicorn", "snipe" };
string joined = string.Join(", ", animals);
like image 20
justin.m.chase Avatar answered Sep 21 '22 19:09

justin.m.chase