【问题标题】:Scala string filter based on split index基于拆分索引的Scala字符串过滤器
【发布时间】:2017-01-30 17:51:40
【问题描述】:

试图写一个函数,将保留输入行的原始结构(不拆分)并根据某个索引进行过滤。

下面的示例尝试过滤输入字符串,以使第 4 个元素(在管道上拆分后)大于 2 个标记

"1||2||3||4||test or not".split("\\|\\|").filter(_.map(line => line.split("\\s")(4).length>2))


I receive the following error;
error: value split is not a member of Char

我该如何解决这个问题?

【问题讨论】:

  • 这种情况下的最终结果是什么? “这||2||是||测试与否”?
  • 第 4 个元素将始终包含多个单词。我想过滤,以便新的数据结构只保留第 4 个元素具有 > 2 个单词的行

标签: arrays string scala filter


【解决方案1】:

这应该做你想做的事。您可能想为该函数找到一个更好的名称。

def predicate(index: Int, minSize: Int)(s: String): Boolean =
    s.split("\\|\\|") match {
        case e if e.length > index => e(index).split("\\s").length > minSize
        case _ => false
    }


lines.filter(predicate(4, 2))

【讨论】:

    【解决方案2】:

    这样写,你就能看到省略的参数是一个String,然后是一个Char

        "this||2||is||my||test or not".split("\\|\\|").filter { someString =>
          someString.map { someChar =>
            someChar
          }
          true
        }
      }
    

    filter 的长格式是someCollection.filter(element => booleanExpression)map 类似。每次应用.filter.map 时,您都会解构集合并对元素应用操作。 "...".split("...") 的元素是字符串。字符串的“元素”是字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多