【问题标题】:Filter the string removing all elements which have the same element as in another string in the same index过滤字符串,删除所有与同一索引中的另一个字符串具有相同元素的元素
【发布时间】:2023-01-18 02:21:13
【问题描述】:

正如标题所说,我想实现一个函数 pool,它在删除给定字符串的所有元素后返回一个字符列表,这些元素是与另一个字符串在同一索引中的相同字母。由于我为获取给定索引中的元素而编写的代码,它给了我一个 StringIndexOutOfBoundsExceptions。我该如何解决这个问题?

我的实现

def pool(secret: String, word: String) : List[Char] = { 
    secret.filterNot(x => secret.apply(x) == word.apply(x)).toList
}

测试用例

pool("chess", "caves") => List(h, e, s)
pool("chess", "swiss") => List(c, h, e)

错误信息

java.lang.StringIndexOutOfBoundsException: String index out of range: 99
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1515)
at scala.collection.StringOps$.apply$extension(StringOps.scala:188)
at $anonfun$pool$1(<console>:3)
at $anonfun$pool$1$adapted(<console>:3)
at scala.collection.StringOps$.filterNot$extension(StringOps.scala:1264)
at pool(<console>:3)
... 32 elided

【问题讨论】:

    标签: scala


    【解决方案1】:

    x 是字符,String.apply 接受一个指数. c 有 ascii 码 99,所以当你执行 "caves".apply('c') 时,它会尝试访问索引 99 处“洞穴”中的字符,并抛出错误,因为字符串不够长。

    无论如何,您的方法效率极低,因此不值得修复。

    试试这样的事情:

    secret
      .zipAll(word, 0.toChar, 0.toChar)
      .collect { case (a,b) if a != b && a != 0.toChar => a }
      .mkString
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      相关资源
      最近更新 更多