Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split strings into characters in Scala

People also ask

How to split strings in Scala?

Use the split() Method to Split a String in Scala Scala provides a method called split() , which is used to split a given string into an array of strings using the delimiter passed as a parameter. This is optional, but we can also limit the total number of elements of the resultant array using the limit parameter.

How does split work in Scala?

Split is used to divide the string into several parts containing inside an array because this function return us array as result. We can also limit our array elements by using the 'limit' parameter. Otherwise, it will just contain all the parameters from the string that has been spitted.

How do you check if a string contains a substring in Scala?

Use the contains() Function to Find Substring in Scala Here, we used the contains() function to find the substring in a string. This function returns a Boolean value, either true or false.


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.

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")

You can use toList as follows:

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

If you want an array, you can use toArray

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

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:

"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.


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

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