Scala中字符串的替换

sh7euo9m  于 2022-12-23  发布在  Scala
关注(0)|答案(5)|浏览(240)

我正在尝试创建一个方法来转换字符串中的字符,特别是将所有“0”转换为“”。这是我正在使用的代码:

def removeZeros(s: String) = {
    val charArray = s.toCharArray
    charArray.map( c => if(c == '0') ' ')
    new String(charArray)
}

有没有更简单的方法?以下语法无效:

def removeZeros(s: String) = 
  new String(s.toCharArray.map( c => if(c == '0') ' '))
0kjbasz6

0kjbasz61#

可以直接Map字符串:

def removeZero(s: String) = s.map(c => if(c == '0') ' ' else c)

或者,您可以使用replace

s.replace('0', ' ')
ljo96ir5

ljo96ir52#

很简单:

scala> "FooN00b".filterNot(_ == '0')
res0: String = FooNb

要将某些字符替换为其他字符:

scala> "FooN00b" map { case '0' => 'o'  case 'N' => 'D'  case c => c }
res1: String = FooDoob

用任意数量的字符替换一个字符:

scala> "FooN00b" flatMap { case '0' => "oOo"  case 'N' => ""  case c => s"$c" }
res2: String = FoooOooOob
1cosmwyk

1cosmwyk3#

根据伊格纳西奥Alorre的说法,如果你想把其他字符替换成字符串:

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")
pokxtpni

pokxtpni4#

执行此操作的首选方法是使用s.replace('0', ' ')
出于训练的目的,您也可以使用尾递归来实现这一点。

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"

并且更一般地:

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"
erhoui1w

erhoui1w5#

/**
 * how to replace a empty character in string
 */
val name = "Jeeta"
val afterReplace = name.replace("" + 'a', "")

相关问题