简体   繁体   中英

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

How do I best perfrom this?

Thanks in advance

Use 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 . In .NET, string s are immutable and therefore String.TrimStart does not modify the string that the method is invoked on. That is, s.TrimStart('0') does not modify s . If you want to modify s you must say

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM