Home » Scala language

How to convert a string with newline into a list of strings in Scala?

Converting a string with newline into a list of strings: In Scala, you can do multiple things, and converting a string into a sequence/list is one of them. Using two or three different methods that are inbuilt in Scala you can easily convert a string with newline characters into a sequence/list of Strings.
Submitted by Shivang Yadav, on July 29, 2019

A string is a sequence of characters and it can contain multiple lines, for this, the string uses the newline character \n. And, we can separate each newline into a string and store them as a list of strings.

For this purpose, we can use some methods that are built-in in the Scala language. The logics rest the same, storing all contents in a string until a newline is encountered and after the newline, the contents till the next are stored in the second string of the sequence and so on.

Methods that are used,

  1. string.split('char'):
    This function splits the string after the occurrence of the specified character. This means that when the character occurs the string will get split.
  2. toVector:
    This method stores this split string into a list that is to be returned.

Program:

object MyClass {
    
    def convertStringToSeq(s: String): Seq[String] =
        s.split("\n").toVector 
        
        def main(args: Array[String]) {
            val str = "Hello!\nthisis\nInclude Help"
            val conlist = convertStringToSeq(str)
            println(conlist)
    }
    
}

Output

Vector(Hello!, thisis, Include Help)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.