MARK
MARK

Reputation: 2362

Getting values stored in some specific indices in an array in Scala

I have a String array and let us suppose that I want to get the third , 7th and 11th members from the array and apply some function to these arrays.

I know that I can do it the java way like using if statement but I want to do it the scala way

As an addition to the question, let us suppose that original string has multiple words seperated by comma. I want to apply some mentioned to the third, 7th and 11th members, while rest of the string remains the same.

In other words if the input string was

i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11

I want to change it to

i1, i2, f(i3), i4, i5, i6, f(i7), i8, i9, i10, f(i11)

Currently, I am doing it this way

def process(lin1:String):String=
    {

            val line:Array[String]=lin1.split(";")
            var iLength=line.length
            var iTotalColumns=28
            var i=0
            var output:String=""
            for( i<-0 to iLength-1){


                var sTemp=line(i)
                if((i==3)||(i==7)||(i==11))

Upvotes: 0

Views: 163

Answers (1)

Shadowlands
Shadowlands

Reputation: 15074

Try this:

def selective(f: String => String, ixs: Seq[Int])(in: String) =
  in.split(";").zipWithIndex
    .map { 
      case (str, ix) if (ixs.contains(ix)) => f(str)
      case other => other._1
    }

Example call:

scala> val input = "entry1;entry2;entry3;entry4;entry5;entry6;entry7;entry8;entry9;entry10;entry11"
input: String = entry1;entry2;entry3;entry4;entry5;entry6;entry7;entry8;entry9;entry10;entry11

scala> selective(_.toUpperCase, List(2,6,10))(input)
res3: Array[String] = Array(entry1, entry2, ENTRY3, entry4, entry5, entry6, ENTRY7, entry8, entry9, entry10, ENTRY11)

Upvotes: 1

Related Questions