0

I've a string that looks like an array that shown below. How can I transform this string to an array like shown below? I've tried this solution but I got an error from Xcode(Command failed due to signal segmentation fault 11) and I've thought this way too hard for compiler.

String:

var list = "<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>"

Target Array:

var array = [<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>]

And when I tried let arr = list.characters.split {$0 == ","} prints:

[Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e40, _countAndFlags: 9223372036854775811, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e48, _countAndFlags: 9223372036854775812, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e52, _countAndFlags: 9223372036854775817, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e66, _countAndFlags: 9223372036854775816, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e78, _countAndFlags: 9223372036854775815, _owner: nil))]

With whitespace(let arr = list.characters.split {$0 == ", "}) gives compiler error:

  • Command failed due to signal segmentation fault 11
Community
  • 1
  • 1
do it better
  • 4,627
  • 6
  • 25
  • 41

2 Answers2

1

There is a function that does that, componentsSeparatedByString

var array = list.componentsSeparatedByString(", ")
Lukas
  • 3,423
  • 2
  • 14
  • 26
0

Would this work:

var list = "<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>"

do {
    //Create a reggae and replace "," with any following spaces with just a comma
    let regex = try NSRegularExpression(pattern: ", +", options: NSRegularExpressionOptions.CaseInsensitive)
    list = regex.stringByReplacingMatchesInString(list, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, list.characters.count), withTemplate: ",")
    var array = list.characters.split { $0 == ","}.map(String.init)
} catch {
    //Bad regex created
}

EDIT: Updated the example to remove componentsSeparatedByString for a native swift way. The problem with your example is that the resulting array did not contain strings but what seems to be an internal class called CharacterView. Mapping these back into Strings produces the desired output.

Output:

[
    "<strong>UP</strong>", 
    "<strong>UP</strong>", 
    "<strong>DOWN</strong>", 
    "<strong>UP</strong>"
]
TheRobDay
  • 511
  • 3
  • 7