1

There are some Strings like:

"A,C,D"   "A,C"   "A,B"   "B,C"   "D,F"   "G,D,H"  

If I want to filter those Strings by the key: A,C. That means, if the String contains A or C, I will take it. For example, through this rule, I will get:

"A,C,D"   "A,C"   "A,B"   "B,C"

How should I code this function?

user unknown
  • 35,537
  • 11
  • 75
  • 121
Wangkkkkkk
  • 15
  • 5
  • 4
    What do you have so far? Put your samples in a list, and search for a function in List, which looks promising. Write a function which can solve solve your problem for a single case. Combine the function with the list function. – user unknown Feb 05 '18 at 06:30
  • `.filter(_.matches(".*(A|C).*"))` – jwvh Feb 05 '18 at 06:46

3 Answers3

0

You should try this for yourself as this is a good learning exercise for beginners in Scala like you mentioned!

So here is an idea on how you could do it! There are a million other ways, but this is just for you to get started!

scala> val l = List("A,C,D",   "A,C",   "A,B",   "B,C",   "D,F",   "G,D,H")
l: List[String] = List(A,C,D, A,C, A,B, B,C, D,F, G,D,H)

scala> l.filter(elem => elem.contains("A") || elem.contains("C"))
res1: List[String] = List(A,C,D, A,C, A,B, B,C)

scala>
joesan
  • 13,963
  • 27
  • 95
  • 232
0

assuming your input is string as below,

scala> val input = """"A,C,D"   "A,C"   "A,B"   "B,C"   "D,F"   "G,D,H""""
input: String = "A,C,D"   "A,C"   "A,B"   "B,C"   "D,F"   "G,D,H"

you can split by " and then filter out empty strings. Then filter those which contains A | C

scala> input.split("\"").map(_.trim).filter(_.nonEmpty).filter(e => e.contains("A") || e.contains("C"))
res1: Array[String] = Array(A,C,D, A,C, A,B, B,C)

Or you can also apply regex pattern something like .*A.*|.*C.*,

scala> input.split("\"").filter(_.nonEmpty).filter(_.matches(".*(A|C).*"))
res2: Array[String] = Array(A,C,D, A,C, A,B, B,C)

Also see:

filter a List according to multiple contains

prayagupa
  • 30,204
  • 14
  • 155
  • 192
0
val samples = List ("A,C,D", "A,C", "A,B", "B,C", "D,F", "G,D,H")
samples.filter (s => s.contains ('A') || s.contains ('C')) 
> List(A,C,D, A,C, A,B, B,C)

Note how you raised the important keywords contains and filter (though you will not always that lucky).

user unknown
  • 35,537
  • 11
  • 75
  • 121