×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

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

By IncludeHelp Last updated : October 20, 2024

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.

Converting a string with newline into 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.

Scala program to convert a string with newline into a list of strings

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.