Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a String in Scala

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') ' '))
like image 534
Hanxue Avatar asked Sep 10 '25 16:09

Hanxue


2 Answers

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', ' ')
like image 187
Lee Avatar answered Sep 12 '25 06:09

Lee


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
like image 30
Randall Schulz Avatar answered Sep 12 '25 05:09

Randall Schulz