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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.