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
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.
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.
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.
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');
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