Avinash12388
Avinash12388

Reputation: 1102

Convert array in quotation marks to just an array

I currently have a string, that's supposed to be an Array:

var content = "['A','B','C']"
//What I want -> var content = ['A', 'B', 'C']

I need to remove the quotation marks, so that it's just an Array, i.e. String to Array. How would one attempt that?

Upvotes: 1

Views: 1357

Answers (3)

Mindhavok
Mindhavok

Reputation: 457

You could do this one:

let arr = content.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "['],")).filter({!$0.isEmpty})

Explanation:

  • First, we split the string into an array based upon separators like: [, ', ,, ]

  • We now have an array with some empty strings, we use filter() to remove them.

  • And Voila !

Warning:

like @nebs' warning, carefull with this solution. If your string is composed by more complexe strings (ex: "['Hello [buddy]', 'What's up?', 'This is a long text, or not?']"), especially string composed with the separators, you will get an array that will not match with your expected result.

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70119

This looks similar to JSON syntax except that the single quotes should be double quotes.

Well then, let's just do that:

let source = "['A','B','C']"

Replace single quotes with double quotes:

let content = source.stringByReplacingOccurrencesOfString("'", withString: "\"")

Then convert the String to NSData (becomes valid JSON):

guard let data = content.dataUsingEncoding(NSUTF8StringEncoding) else { fatalError() }

Finally, convert the JSON data back to a Swift array of Strings:

guard let arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else { fatalError() }

Result:

print(arrayOfStrings)

["A", "B", "C"]

print(arrayOfStrings[1])

"B"

Upvotes: 2

nebs
nebs

Reputation: 4989

Here's a semi-hacky solution to your specific example.

let content = "['A','B','C']"
var characters = content.characters
characters.removeFirst(2) // Remove ['
characters.removeLast(2)  // Remove ']
let contentArray = String(characters).componentsSeparatedByString("','")
print(contentArray) // ["A", "B", "C"]

Disclaimer/Warning: This solution isn't robust as it expects your array to only contain objects wrapped in ' characters. It will however work for any length of string (e.g. replacing A with foo will work).

If your actual content string is any more complex than what you have here then I would take Rob's advice and try JSON serialization (especially if this string comes from a place you don't control like the server).

Upvotes: 0

Related Questions