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.
string s = ",liger, unicorn, snipe";
s.TrimStart(',');
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
.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())
here is an easy way to not produce the leading comma to begin with:
string[] animals = { "liger", "unicorn", "snipe" };
string joined = string.Join(", ", animals);
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