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?
我需要去掉引号,这样它就是一个数组,也就是说,从字符串到数组。怎么做呢?
3 个解决方案
#1
1
This looks similar to JSON syntax except that the single quotes should be double quotes.
这看起来类似于JSON语法,除了单引号应该是双引号。
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):
然后将字符串转换为NSData(变为有效的JSON):
guard let data = content.dataUsingEncoding(NSUTF8StringEncoding) else { fatalError() }
Finally, convert the JSON data back to a Swift array of Strings:
最后,将JSON数据转换回Swift字符串数组:
guard let arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else { fatalError() }
Result:
结果:
print(arrayOfStrings)
["A", "B", "C"]
(“A”、“B”、“C”)
print(arrayOfStrings[1])
"B"
“B”
#2
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).
免责声明/警告:该解决方案并不健壮,因为它期望您的数组只包含“字符”包装的对象。但是它对任何长度的字符串都有效(例如用foo替换A就可以)。
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).
如果您的实际内容字符串比这里的更复杂,那么我将采纳Rob的建议并尝试JSON序列化(特别是如果这个字符串来自一个您不喜欢服务器的地方)。
#3
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.我们现在有一个带一些空字符串的数组,我们使用filter()来删除它们。
-
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.
就像@nebs的警告一样,小心这个解决方案。如果你的字符串是由更复杂的字符串组成的(例如:“['Hello [buddy]]', 'What's up?,“这是一个长文本,或者不是?”),特别是用分隔符组成的字符串,您将得到一个与预期结果不匹配的数组。
#1
1
This looks similar to JSON syntax except that the single quotes should be double quotes.
这看起来类似于JSON语法,除了单引号应该是双引号。
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):
然后将字符串转换为NSData(变为有效的JSON):
guard let data = content.dataUsingEncoding(NSUTF8StringEncoding) else { fatalError() }
Finally, convert the JSON data back to a Swift array of Strings:
最后,将JSON数据转换回Swift字符串数组:
guard let arrayOfStrings = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String] else { fatalError() }
Result:
结果:
print(arrayOfStrings)
["A", "B", "C"]
(“A”、“B”、“C”)
print(arrayOfStrings[1])
"B"
“B”
#2
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).
免责声明/警告:该解决方案并不健壮,因为它期望您的数组只包含“字符”包装的对象。但是它对任何长度的字符串都有效(例如用foo替换A就可以)。
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).
如果您的实际内容字符串比这里的更复杂,那么我将采纳Rob的建议并尝试JSON序列化(特别是如果这个字符串来自一个您不喜欢服务器的地方)。
#3
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.我们现在有一个带一些空字符串的数组,我们使用filter()来删除它们。
-
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.
就像@nebs的警告一样,小心这个解决方案。如果你的字符串是由更复杂的字符串组成的(例如:“['Hello [buddy]]', 'What's up?,“这是一个长文本,或者不是?”),特别是用分隔符组成的字符串,您将得到一个与预期结果不匹配的数组。