替换Scala中String中的字符

时间:2014-01-21 15:03:56

标签: string scala dictionary functional-programming

我正在尝试创建一个转换String中字符的方法,特别是将所有'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') ' '))

5 个答案:

答案 0 :(得分:37)

您可以直接映射字符串:

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

或者您可以使用replace

s.replace('0', ' ')

答案 1 :(得分:24)

很简单:

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

执行此操作的首选方法是使用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"

答案 4 :(得分:0)

根据Ignacio 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")