【问题标题】:Replacing characters in a String in Scala在Scala中替换字符串中的字符
【发布时间】:2014-02-11 06:14:27
【问题描述】:

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

【问题讨论】:

    标签: string scala dictionary functional-programming


    【解决方案1】:

    可以直接映射字符串:

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

    您也可以使用replace:

    s.replace('0', ' ')
    

    【讨论】:

    • 你知道如何替换双引号字符吗? "
    • @IgnacioAlorre - 用什么替换它?像s.replace('"', ' ') 这样的东西应该可以工作。
    【解决方案2】:

    很简单:

    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
    

    【讨论】:

    • 我理解这个问题是从字面上删除零。如果你想用另一个字符替换它们,map 可以。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      /**
         how to replace a empty chachter in string
      **/
      val name="Jeeta"
      val afterReplace=name.replace(""+'a',"")
      

      【讨论】:

        【解决方案5】:

        最好的方法是使用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"
        

        【讨论】:

          猜你喜欢
          • 2017-03-20
          • 2014-05-08
          • 2011-12-17
          • 2020-03-08
          • 2011-07-02
          相关资源
          最近更新 更多