【发布时间】: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
例如,有一个字符串 val s = "Test"。你怎么把它分成t, e, s, t?
【问题讨论】:
标签: string scala character-encoding split character
你需要字符吗?
"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")
【讨论】:
您可以使用toList,如下:
scala> s.toList
res1: List[Char] = List(T, e, s, t)
如果你想要一个数组,你可以使用toArray
scala> s.toArray
res2: Array[Char] = Array(T, e, s, t)
【讨论】:
"abc".toList 有效,而"abc".toList() 无效。我在哪里可以找到 scala String 的文档。
其实你不需要做任何特别的事情。 Predef 到 WrappedString 和 WrappedString 中已经有隐式转换 IndexedSeq[Char] 所以你有所有可用的东西,比如:
"Test" foreach println
"Test" map (_ + "!")
Predef 具有比LowPriorityImplicits 中的wrapString 更高优先级的augmentString 转换。所以字符串最终是StringLike[String],这也是字符的Seq。
【讨论】:
StringOps。
Predef 具有比LowPriorityImplicits 中的wrapString 更高优先级的augmentString 转换。对不起,我没有注意到它。谢谢!
另外,应该注意的是,如果你真正想要的不是一个实际的列表对象,而只是对每个字符做一些事情,那么 Strings 可以用作 Scala 中的可迭代字符集合
for(ch<-"Test") println("_" + ch + "_") //prints each letter on a different line, surrounded by underscores
【讨论】: