string 在 Scala 中替换字符串中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21261737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:13:02  来源:igfitidea点击:

Replacing characters in a String in Scala

stringscaladictionaryfunctional-programming

提问by Hanxue

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:

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

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') ' '))

回答by Lee

You can map strings directly:

您可以直接映射字符串:

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

alternatively you could use replace:

或者你可以使用replace

s.replace('0', ' ')

回答by Randall Schulz

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

回答by josh

According to Ignacio Alorre, if you want to replace others chars into string:

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

回答by Jitendra Pradhan

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

回答by moped

The go-to way to do it is to use s.replace('0', ' ')

这样做的首选方法是使用 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"