kaileena
kaileena

Reputation: 141

Eliminate a char from a list of chars in scala

I have this list of chars in Scala:

val a = "(i am(a? list) of(/ chars in  )Scala)".toList

I want to find the position of the first ')' and eliminate it from the list. How can I do that?

What I did (but did not work):

val position = a.tail.indexOf(')')
a.drop(position)

and also tried it with a.take(position). I found out that the methods drop and take are not good for what I need. I want that the method works as follows:

input:  (i am(a? list) of(/ chars in )Scala)
output: (i am(a? list of(/ chars in )Scala)
                     ^

Upvotes: 0

Views: 341

Answers (4)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

Try this:

a.replaceFirst("\\)","")

In Scala REPL:

scala> val a = "(i am(a? list) of(/ chars in  )Scala)"
a: String = (i am(a? list) of(/ chars in  )Scala)


scala> a.replaceFirst("\\)","")
res123: String = (i am(a? list of(/ chars in  )Scala)

scala>

Upvotes: 0

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

In defence of take and drop: these two methods do exactly what you wanted:

val str = "(i am(a? list) of(/ chars in )Scala)"
val idx = str.indexOf(')')
println(str.take(idx) + str.drop(idx + 1))

There is also span, which does both take and drop simultaneously:

val (before, after) = str.splitAt(idx)
println(before + after.tail)

Both versions output

(i am(a? list of(/ chars in )Scala)
(i am(a? list of(/ chars in )Scala)

Upvotes: 1

jwvh
jwvh

Reputation: 51271

The often overlooked patch() will do that.

a.patch(a.indexOf(')'), List(), 1)

Note that indexOf() will give misleading results if the target element is not present.

val result = if (a.contains(')') a.patch(a.indexOf(')'), List(), 1)
             else a

Upvotes: 6

SCouto
SCouto

Reputation: 7928

You can remove the element with a foldLeft

First perform a zipWithIndex to have the index of each char in your list, then with the foldLeft, if the index matchesthe desired index, just don't add that element to the accumulator:

a.zipWithIndex
 .foldLeft(Nil: List[Char])((acc, elem) => if (elem._2 == a.indexOf(')')) acc  else acc:+elem._1)

Result of the a.zipWithIndex

List[(Char, Int)] = List(((,0), (i,1), ( ,2), (a,3), (m,4), ((,5), (a,6), (?,7), ( ,8), (l,9), (i,10), (s,11), (t,12), (),13), ( ,14), (o,15), (f,16), ((,17), (/,18), ( ,19), (c,20), (h,21), (a,22), (r,23), (s,24), ( ,25), (i,26), (n,27), ( ,28), ( ,29), (),30), (S,31), (c,32), (a,33), (l,34), (a,35), (),36))

Final result:

List[Char] = List((, i,  , a, m, (, a, ?,  , l, i, s, t,  , o, f, (, /,  , c, h, a, r, s,  , i, n,  ,  , ), S, c, a, l, a, ))

Final result as a String:

String = (i am(a? list of(/ chars in  )Scala)

Upvotes: 0

Related Questions