Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first 0's (zero) from string in c# 2.0

Tags:

c#

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

like image 291
Peter Avatar asked Nov 24 '10 02:11

Peter


People also ask

How do you remove the first zero from a string?

Approach: We use the StringBuffer class as Strings are immutable. Count leading zeros by iterating string using charAt(i) and checking for 0 at the “i” th indices. Use StringBuffer replace function to remove characters equal to the above count using replace() method.

How do you remove trailing zeros from strings?

Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.

How do you remove leading zeros from a string in C++?

Using Stoi() Method stoi() function in C++ is used to convert the given string into an integer value. It takes a string as an argument and returns its value in integer form. We can simply use this method to convert our string to an integer value which will remove the leading zeros.


1 Answers

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, strings 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');
like image 131
jason Avatar answered Nov 15 '22 07:11

jason