ios 将 Swift 字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25921204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Swift string to array
提问by Mr.KLD
How can I convert a string "Hello" to an array ["H","e","l","l","o"] in Swift?
如何在 Swift 中将字符串“Hello”转换为数组 ["H","e","l","l","o"]?
In Objective-C I have used this:
在Objective-C中,我使用了这个:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
回答by Martin R
It is even easier in Swift:
在 Swift 中更简单:
let string : String = "Hello "
let characters = Array(string)
println(characters)
// [H, e, l, l, o, , , , , ]
This uses the facts that
这使用了以下事实
- an
Array
can be created from aSequenceType
, and String
conforms to theSequenceType
protocol, and its sequence generator enumerates the characters.
- an
Array
可以从 a 创建SequenceType
,并且 String
符合SequenceType
协议,其序列生成器枚举字符。
And since Swift strings have full support for Unicode, this works even with characters outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme clusters (such as , which is actually composed of twoUnicode scalars).
并且由于 Swift 字符串完全支持 Unicode,这甚至适用于“基本多语言平面”之外的字符(例如 )和扩展的字素簇(例如 ,它实际上由两个Unicode 标量组成)。
Update: As of Swift 2,String
does no longer conform to
SequenceType
, but the characters
property provides a sequence of the
Unicode characters:
更新:从 Swift 2 开始,String
不再符合
SequenceType
,但该characters
属性提供了一系列 Unicode 字符:
let string = "Hello "
let characters = Array(string.characters)
print(characters)
This works in Swift 3as well.
这也适用于Swift 3。
Update: As of Swift 4,String
is (again) a collection of its
Character
s:
更新:从 Swift 4 开始,String
(再次)是其Character
s的集合
:
let string = "Hello "
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "", "", " ", ""]
回答by devxoul
Edit (Swift 4)
编辑(斯威夫特 4)
In Swift 4, you don't have to use characters
to use map()
. Just do map()
on String.
在 Swift 4 中,您不必characters
使用map()
. 只需map()
在字符串上做。
let letters = "ABC".map { String(let letters = "ABC".characters.map { String($ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
) }
print(letters) // ["A", "B", "C"]
) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
Or if you'd prefer shorter: "ABC".map(String.init)
(2-bytes )
或者,如果您更喜欢更短的:"ABC".map(String.init)
(2 字节)
Edit (Swift 2 & Swift 3)
编辑(Swift 2 和 Swift 3)
In Swift 2 and Swift 3, You can use map()
function to characters
property.
在 Swift 2 和 Swift 3 中,您可以使用map()
函数来设置characters
属性。
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
Original (Swift 1.x)
原版 (Swift 1.x)
Accepted answer doesn't seem to be the best, because sequence-converted String
is not a String
sequence, but Character
:
接受的答案似乎不是最好的,因为序列转换String
不是String
序列,而是Character
:
let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]
This below works for me:
下面这对我有用:
//array of Characters
let charArr1 = [Character](myString)
//array of String.element
let charArr2 = Array(myString)
for char in myString {
//char is of type Character
}
Reference for a global function map()
is here: http://swifter.natecook.com/func/map/
全局函数的参考在map()
这里:http: //swifter.natecook.com/func/map/
回答by Frédéric Adda
There is also this useful function on String: components(separatedBy: String)
String 上也有这个有用的函数:components(separatedBy: String)
//array of String
var strArr = myString.map { String(let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
//char is of type Character
}
)}
Works well to deal with strings separated by a character like ";" or even "\n"
可以很好地处理由“;”等字符分隔的字符串 甚至 "\n"
回答by ScottyBlades
Updated for Swift 4
为 Swift 4 更新
Here are 3 ways.
这里有3种方法。
var strArr = myString.characters.map { String(extension String {
func letterize() -> [Character] {
return Array(self.characters)
}
}
)}
In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:
在某些情况下,人们真正想要的是一种将字符串转换为每个长度为 1 个字符的小字符串数组的方法。这是一个超级有效的方法:
let charArr = "Cat".letterize()
Swift 3
斯威夫特 3
Here are 3 ways.
这里有3种方法。
let string = "hell0"
let ar = Array(string.characters)
print(ar)
In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:
在某些情况下,人们真正想要的是一种将字符串转换为每个长度为 1 个字符的小字符串数组的方法。这是一个超级有效的方法:
let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\(let characters = "Hello"
var charactersArray: [Character] = []
for (index, character) in enumerate(characters) {
//do something with the character at index
charactersArray.append(character)
}
println(charactersArray)
)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>
Or you can add an extension to String.
或者您可以向 String 添加扩展名。
var strArray = "Hello, playground".Letterize()
extension String {
func Letterize() -> [String] {
return map(self) { String(func letterize() -> [Character] {
return Array(self.characters)
}
) }
}
}
Then you can call it like this:
然后你可以这样称呼它:
let someText = "hello"
let array = someText.map({ String(##代码##) }) // [String]
回答by William Hu
回答by onmyway133
In Swift 4, as String
is a collection of Character
, you need to use map
在 Swift 4 中,作为String
的集合Character
,您需要使用map
回答by Alberto Barrera
Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.
Martin R 的答案是最好的方法,正如他所说,因为 String 符合 SquenceType 协议,您还可以枚举一个字符串,在每次迭代中获取每个字符。
##代码##回答by fabrizioM
You can also create an extension:
您还可以创建扩展:
##代码##回答by Piotr Pszczó?kowski
回答by atolite
An easy way to do this is to map
the variable and return each Character
as a String
:
一个简单的方法是对map
变量并将每个Character
作为 a返回String
:
The output should be ["h", "e", "l", "l", "o"]
.
输出应该是["h", "e", "l", "l", "o"]
.