[英]How to remove first 0's (zero) from string in c# 2.0
I have a string that can contain a value like 000232 or 999999 or 023000 What I am trying to do is to remove the first 000 from the first string, leave the second string and remove the first 0 from the third string and keep 000 to the right 我有一个字符串,可以包含像000232或999999或023000的值我要做的是从第一个字符串中删除第一个000,保留第二个字符串并从第三个字符串中删除第一个0并保持000到对
How do I best perfrom this? 我怎么能最好地完成这个?
Thanks in advance 提前致谢
Use String.TrimStart
: 使用String.TrimStart
:
// s is string
string trimmed = s.TrimStart('0');
Please note that it is essential that you assign the result of String.TrimStart
to a variable of type string
. 请注意,必须将String.TrimStart
的结果String.TrimStart
string
类型的变量。 In .NET, string
s are immutable and therefore String.TrimStart
does not modify the string
that the method is invoked on. 在.NET中, string
s是不可变的,因此String.TrimStart
不会修改调用该方法的string
。 That is, s.TrimStart('0')
does not modify s
. 也就是说, s.TrimStart('0')
不会修改s
。 If you want to modify s
you must say 如果你想修改s
你必须说
s = s.TrimStart('0');
Alternatively, you could use a regex: 或者,您可以使用正则表达式:
using System.Text.RegularExpressions;
string x = "000232";
x = Regex.Replace(x, "^0*", "");
int valueInt;
if (int.TryParse(valueString, out valueInt))
result = valueInt.ToString();
else
result = string.Empty;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.