I am trying to create a method to convert characters within a String, specifically converting all '0' to ' '. This is the code that I am using:
def removeZeros(s: String) = {
val charArray = s.toCharArray
charArray.map( c => if(c == '0') ' ')
new String(charArray)
}
Is there a simpler way to do it? This syntax is not valid:
def removeZeros(s: String) =
new String(s.toCharArray.map( c => if(c == '0') ' '))
You can map strings directly:
def removeZero(s: String) = s.map(c => if(c == '0') ' ' else c)
alternatively you could use replace
:
s.replace('0', ' ')
Very simple:
scala> "FooN00b".filterNot(_ == '0')
res0: String = FooNb
To replace some characters with others:
scala> "FooN00b" map { case '0' => 'o' case 'N' => 'D' case c => c }
res1: String = FooDoob
To replace one character with some arbitrary number of characters:
scala> "FooN00b" flatMap { case '0' => "oOo" case 'N' => "" case c => s"$c" }
res2: String = FoooOooOob
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