C# 如何修剪字符串中的前导逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/73629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I Trim the leading comma in my string
提问by Keng
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#?
在我熟悉的其他语言中,我可以只做一个 string.trim(",") 但我怎么能在 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.
关于 StartTrim 函数有很多来回讨论。正如一些人指出的那样,StartTrim 不会影响主要变量。然而,考虑到数据与问题的构建,我对接受哪个答案感到困惑。确实,问题只希望修剪第一个字符而不是最后一个字符(如果 anny),但是,数据末尾永远不会有“,”。因此,话虽如此,我将接受第一个答案,即使用分配给新变量的 StartTrim。
采纳答案by RickL
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
回答by Bob King
if (s.StartsWith(",")) {
s = s.Substring(1, s.Length - 1);
}
回答by DevelopingChris
string s = ",liger, unicorn, snipe";
s.TrimStart(',');
回答by Kieran Benton
string t = ",liger, unicorn, snipe".TrimStart(new char[] {','});
回答by pilsetnieks
The same way as everywhere else: string.trim
和其他地方一样:string.trim
回答by Matt Dawdy
string s = ",liger, tiger";
if (s.Substring(0, 1) == ",")
s = s.Substring(1);
回答by chakrit
Did you mean trim all instances of "," in that string?
您的意思是修剪该字符串中所有“,”的实例吗?
In which case, you can do:
在这种情况下,您可以执行以下操作:
s = s.Replace(",", "");
回答by Akselsson
",liger, unicorn, snipe".Trim(',') -> "liger, unicor, snipe"
",liger, unicorn, snipe".Trim(',') -> "liger, unicor, snipe"
回答by Magus
Try string.Trim(',') and see if that does what you want.
尝试 string.Trim(',') ,看看它是否符合您的要求。
回答by Clinton Pierce
Just use Substring to ignore the first character (or assign it to another string);
只需使用 Substring 忽略第一个字符(或将其分配给另一个字符串);
string o = ",liger, unicorn, snipe";
string s = o.Substring(1);
回答by Jay Bazuzi
.net strings can do Trim() and TrimStart(). Because it takes params
, you can write:
.net 字符串可以执行 Trim() 和 TrimStart()。因为它需要params
,你可以写:
",liger, unicorn, snipe".TrimStart(',')
and if you have more than one character to trim, you can write:
如果您要修剪多个字符,则可以这样写:
",liger, unicorn, snipe".TrimStart(",; ".ToCharArray())