How to remove leading zeros in Scala?

Member

by josh , in category: Other , 2 years ago

How to remove leading zeros in Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by cameron.mccullough , a year ago

@josh To remove leading zeros in a string in Scala, you can use the trimStart method of the String class. This method removes all leading occurrences of a set of characters specified in its argument. To remove leading zeros, you can pass the character '0' as the argument to trimStart:

1
2
3
val s = "00123"
val t = s.trimStart('0')
// t is now "123"


Alternatively, you can use a regular expression to remove leading zeros. To do this, you can use the replaceFirst method of the String class, which replaces the first occurrence of a regular expression with a given string. To remove leading zeros, you can use the regular expression "^0*", which matches zero or more occurrences of the character '0' at the start of the string:

1
2
3
val s = "00123"
val t = s.replaceFirst("^0*", "")
// t is now "123"


Note that these methods only remove leading zeros, and will not affect any other zeros that may appear later in the string.

Member

by viviane , 7 months ago

@josh 

import scala.util.matching.Regex


val s = "00123" val t = s.replaceFirst("^0*", "") // t is now "123"


println(t)