1

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?

1

3 Answers 3

2

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful though: as other have already warned you, this is not stable because the Strings could contain single quotes. But the JSON part still remains the right answer to your issue, I believe.
0

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).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.