-2

I have a string that looks like this:

let str = "One;Two;Three;Four;Five"

How do I put every value in an array, so each value is separated with the ";" sign.

I have tried to iterate but that does not feel right. Then I also want to filter the result, for example get all values that contains the letter "o".

Any help is appreciated.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107

1 Answers1

1

Pretty simple, use these native functions:

Start by importing Foundation, UIKit or Cocoa (usually Foundation is default).

1: Your string:

let str = "One;Two;Three;Four;Five"

2: Separate each value from the ; sign into an array:

let arr = str.components(separatedBy: ";") // ["One", "Two", "Three", "Four", "Five"]

3: Filter the result:

let containsO = arr.filter({ $0.contains("o")}) // Two, Four

3: Filter the result localized and case insensitive

let caseSensativeO = arr.filter({ $0.localizedCaseInsensitiveContains("o")}) // One, Two, Four
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • 1
    The OP might want also a caseInsensitive search `let containsO = arr.filter({ $0.range(of: "o", options: .caseInsensitive) != nil })` – Leo Dabus Apr 08 '17 at 21:56
  • 1
    You'll need to `import Foundation` (or `UIKit` or `Cocoa`) for that to work. – vacawama Apr 08 '17 at 21:59
  • 1
    or localizedCaseInsensitiveContains `let containsO = arr.filter({ $0.localizedCaseInsensitiveContains("o") })` – Leo Dabus Apr 08 '17 at 22:02