How to break lines into characters in Scala

For example, there is a string val s = "Test" . How do you divide it into t, e, s, t ?

+42
string split scala character character-encoding
Feb 19 '11 at 16:40
source share
4 answers

You can use toList as follows:

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

If you need an array, you can use toArray

 scala> s.toArray res2: Array[Char] = Array(T, e, s, t) 
+47
Feb 19 '11 at 16:42
source share

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? Ok, this is tougher.

 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") 
+56
Feb 20 2018-11-11T00:
source share

In addition, it should be noted that if what you really want is not an actual object of the list, but simply to do something that is each character, then strings can be used as iterative collections of characters in Scala

 for(ch<-"Test") println("_" + ch + "_") //prints each letter on a different line, surrounded by underscores 
+5
Feb 19 '11 at 16:54
source share

In fact, you do not need to do anything special. There is already an implicit conversion to Predef to WrappedString and WrappedString extends IndexedSeq[Char] , so you have all the useful properties available in it, for example:

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

Edit

Predef has Predef transformation, which has higher priority than wrapString to LowPriorityImplicits . So, String ends with StringLike[String] , that is, also Seq characters.

+5
Feb 19 '11 at 16:59
source share



All Articles