string 如何在Scala中将字符串拆分为字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5052042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split strings into characters in Scala
提问by sam
For example, there is a string val s = "Test"
. How do you separate it into t, e, s, t
?
例如,有一个字符串 val s = "Test"
。你怎么把它分成t, e, s, t
?
回答by Rex Kerr
Do you need characters?
你需要人物吗?
"Test".toList // Makes a list of characters
"Test".toArray // Makes an array of characters
Do you need bytes?
你需要字节吗?
"Test".getBytes // Java provides this
Do you need strings?
你需要字符串吗?
"Test".map(_.toString) // Vector of strings
"Test".sliding(1).toList // List of strings
"Test".sliding(1).toArray // Array of strings
Do you need UTF-32 code points? Okay, that's a tougher one.
您需要 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")
回答by aioobe
You can use toList
as follows:
您可以toList
按如下方式使用:
scala> s.toList
res1: List[Char] = List(T, e, s, t)
If you want an array, you can use toArray
如果你想要一个数组,你可以使用 toArray
scala> s.toArray
res2: Array[Char] = Array(T, e, s, t)
回答by tenshi
Actually you don't need to do anything special. There is already implicit conversion in Predef
to WrappedString
and WrappedString
extends IndexedSeq[Char]
so you have all goodies that available in it, like:
其实你不需要做任何特别的事情。已经有隐式转换Predef
到WrappedString
和WrappedString
扩展,IndexedSeq[Char]
所以你有所有可用的东西,比如:
"Test" foreach println
"Test" map (_ + "!")
Edit
编辑
Predef
has augmentString
conversion that has higher priority than wrapString
in LowPriorityImplicits
. So String end up being StringLike[String]
, that is also Seq
of chars.
Predef
具有augmentString
比wrapString
in更高优先级的转换LowPriorityImplicits
。所以 String 最终是StringLike[String]
,那也是Seq
字符。
回答by Dave Griffith
Additionally, it should be noted that if what you actually want isn't an actual list object, but simply to do something which each character, then Strings can be used as iterable collections of characters in Scala
此外,应该注意的是,如果您真正想要的不是实际的列表对象,而只是对每个字符执行某些操作,那么字符串可以用作 Scala 中的可迭代字符集合
for(ch<-"Test") println("_" + ch + "_") //prints each letter on a different line, surrounded by underscores