How to Remove the Leading Zeroes From a Text String

How to Remove the Leading Zeroes From a Text String thumbnail
Leading zeroes can break programs or display data incorrectly.

Manually removing leading zeroes from a string when you're programming is time-consuming and impractical if you write a program that needs to manipulate the string without those zeroes. If your text string is a number, you can generally convert the string to an integer and then back to a string to remove the leading zeroes. If the zeroes precede actual text, you'll need to remove them with a regular expression. These strategies work in the Ruby, Python and C++ programming languages, among others.

Instructions

    • 1

      Type the following code in Ruby to remove leading zeroes from a number saved as a string, assuming your string is assigned to the variable "@t": @t.to_i.to_s. Use this code if your string contains letters: @t.gsub!(/^0{n}+/,'').

    • 2

      Enter the following code to strip leading zeroes from a string in Python, assuming your string is "mystring": mystring = mystring.lstrip('0').

    • 3

      Use the following code to trim leading zeroes from a string in C++, assuming your string is "t": string b = t.TrimStart('0');. This gives you a string "b" without the leading zeroes.

Related Searches:

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images

Comments

Related Ads

Featured