【问题标题】:How to split strings into characters in Scala如何在Scala中将字符串拆分为字符
【发布时间】:2011-06-30 10:30:22
【问题描述】:

例如,有一个字符串 val s = "Test"。你怎么把它分成t, e, s, t

【问题讨论】:

  • 需要什么输出?您可以将其转换为列表 S.toList 输出 List[Char] = List(T, e, s, t)

标签: string scala character-encoding split character


【解决方案1】:

你需要字符吗?

"Test".toList    // Makes a list of characters
"Test".toArray   // Makes an array of characters

你需要字节吗?

"Test".getBytes  // Java provides this

你需要字符串吗?

"Test".map(_.toString)    // Vector of strings
"Test".sliding(1).toList  // List of strings
"Test".sliding(1).toArray // Array of strings

您需要 UTF-32 代码点吗?好吧,那就更难了。

def UTF32point(s: String, idx: Int = 0, found: List[Int] = Nil): List[Int] = {
  if (idx >= s.length) found.reverse
  else {
    val point = s.codePointAt(idx)
    UTF32point(s, idx + java.lang.Character.charCount(point), point :: found)
  }
}
UTF32point("Test")

【讨论】:

  • 即使知道代码点,您也应该在这里得到公认的答案。虽然我怀疑 OP 会欣赏其中的微妙之处。
【解决方案2】:

您可以使用toList,如下:

scala> s.toList         
res1: List[Char] = List(T, e, s, t)

如果你想要一个数组,你可以使用toArray

scala> s.toArray
res2: Array[Char] = Array(T, e, s, t)

【讨论】:

  • 对于那些看到这一点的人,应该尽可能首选 toCharArray。 toList 非常缓慢。每个字符原语都成为一个 Character 对象。列表中的每个链接也是一个对象。 2 个字节变成 12+2+12+2=28 个字节。我们不能再有快速和随机的访问。但是,如果您只是在玩游戏或编写 Hello World,那就试试吧,但不要指望它能很好地扩展。
  • 我是 Scala 新手。为什么"abc".toList 有效,而"abc".toList() 无效。我在哪里可以找到 scala String 的文档。
  • 在这里找到答案,stackoverflow.com/questions/6643030/…,没关系。
【解决方案3】:

其实你不需要做任何特别的事情。 PredefWrappedStringWrappedString 中已经有隐式转换 IndexedSeq[Char] 所以你有所有可用的东西,比如:

"Test" foreach println
"Test" map (_ + "!") 

编辑

Predef 具有比LowPriorityImplicits 中的wrapString 更高优先级的augmentString 转换。所以字符串最终是StringLike[String],这也是字符的Seq

【讨论】:

  • 我认为它实际上是通过StringOps
  • @Kevin Wright:你是对的。 Predef 具有比LowPriorityImplicits 中的wrapString 更高优先级的augmentString 转换。对不起,我没有注意到它。谢谢!
【解决方案4】:

另外,应该注意的是,如果你真正想要的不是一个实际的列表对象,而只是对每个字符做一些事情,那么 Strings 可以用作 Scala 中的可迭代字符集合

for(ch<-"Test") println("_" + ch + "_") //prints each letter on a different line, surrounded by underscores

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 2014-04-01
    • 1970-01-01
    • 2013-02-04
    • 2020-12-14
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多