0

I have a file as below,

AB*xyz*1234~
CD*mny*769~
MN*bvd*2345~
AB*zar*987~

here i would like to split the data using(*) and line always ends with ~.

code.

val bufferedSource = Source.fromFile(sample.txt)
    var array = Array[String]()
    for (line <- bufferedSource.getLines()) {
      array = line.split("\\~")
      val splittedRow=array.split("\\*")

      }

I want output as below which should be first words from all lined,

Array(AB,CD,MN,AB).

3 Answers 3

1

You can simply do

Source.fromFile(filename).getLines().map(line => line.split("\\*").head).toArray
//res0: Array[String] = Array(AB, CD, MN, AB)
Sign up to request clarification or add additional context in comments.

Comments

1

This is probably better achieved by mapping over the lines from the file, and selecting the part of the string you want to keep:

val array = 
  Source.fromFile(sample.txt)  // Open the file
    .getLines()                // get each line
    .toArray                   // as an array
    .map(s => s.split("\\*").head)  // Then select just the first part
                                    // of the line, split by * characters

3 Comments

Thanks for your reply.. i am getting the output as [Ljava.lang.String;@a92be4f .
i converted the array to list and got the expected output.
That's because Arrays don't print out their contents like Lists do.
0

You can also use collect to get what you want

val s = Source.fromFile("fileName").getLines().collect{
  case e => e.split("\\*").apply(0)
}.toArray
//s: Array[String] = Array(AB, CD, MN, AB)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.