We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

remove the first zero from a number

Tech_Men
Tech_Men asked
on
Medium Priority
221 Views
Last Modified: 2010-04-16
hi there ,

in the func i geting this kind of number 03178596
i want to dispose the zero but only if its the first digit in the num

how can i do it ?

thanks ...
Comment
Watch Question

You could convert it to a number and then back to a string again:

   string numResult="03178596";
   string trimedResult=long.parse(numResult).ToString();

Or write a specialized trim function (probably faster)
public class utilClass
{
 public static string trimLeading(string s, char trimChar)
 {
    int startOffset=0;
    while(startOffset<s.Length-1) //If it is ALL 0's then leave the last one there
    {
       if (s[startOffset]!=trimChar)
         break;   //Found 1st non-trimChar
       startOffset++;
    }
      return s.SubString(startOffset);
 }
}
Then call it like this:
    string numResult="03178596";
    string trimedResult=utilClass.trimLeading(numResult, '0');

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
                               static void remove_zero(ref string num)
            {
                  while(num.StartsWith("0"))
                        num = num.Remove(0,1);
                  
            }
rahul_r_jadhav's solution is not as efficient (though quite elegant).  Each time
  num = num.Remove(0,1);
is called, a new string is created, which might slow your application down (a few seconds) with unnecessary garbage collections.
Carl TawnSenior Systems and Integration Developer
CERTIFIED EXPERT

Commented:
Simply casting it to a numeric data type should drop any leading zeros:

i.e.

        string num = "0123456789";
        long lnum = long.Parse(num);
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.