Replacing characters in a String in Scala
76,357
Solution 1
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', ' ')
Solution 2
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
Solution 3
According to Ignacio Alorre, if you want to replace others chars into string:
def replaceChars (str: String) = str.map(c => if (c == '0') ' ' else if (c =='T') '_' else if (c=='-') '_' else if(c=='Z') '.' else c)
val charReplaced = replaceChars("N000TZ")
Solution 4
The go-to way to do it is to use s.replace('0', ' ')
Just for training purposes you might use tail-recursion to achieve that as well.
def replace(s: String): String = {
def go(chars: List[Char], acc: List[Char]): List[Char] = chars match {
case Nil => acc.reverse
case '0' :: xs => go(xs, ' ' :: acc)
case x :: xs => go(xs, x :: acc)
}
go(s.toCharArray.toList, Nil).mkString
}
replace("01230123") // " 123 123"
and more generally:
def replace(s: String, find: Char, replacement: Char): String = {
def go(chars: List[Char], acc: List[Char]): List[Char] = chars match {
case Nil => acc.reverse
case `find` :: xs => go(xs, replacement :: acc)
case x :: xs => go(xs, x :: acc)
}
go(s.toCharArray.toList, Nil).mkString
}
replace("01230123", '0', ' ') // " 123 123"
Solution 5
/**
how to replace a empty chachter in string
**/
val name="Jeeta"
val afterReplace=name.replace(""+'a',"")
Related videos on Youtube
Author by
Hanxue
I am currently a full-stack software engineer based in Beijing, as well as traditional internal martial artist.
Updated on January 14, 2020Comments
-
Hanxue over 4 years
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') ' '))
-
Randall Schulz over 10 yearsI understood the question to be literally removing the zeros. If you want to replace them with another single character,
map
works. -
Ignacio Alorre almost 5 yearsDo you know how to to replace double quote character? "
-
Lee almost 5 years@IgnacioAlorre - Replace it with what? Something like
s.replace('"', ' ')
should work.