简体   繁体   English

将 Swift 字符串转换为数组

[英]Convert Swift string to array

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];
}

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 a SequenceType , and可以从SequenceType创建一个Array ,并且
  • String conforms to the SequenceType protocol, and its sequence generator enumerates the characters. 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 two Unicode 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 3 as well.这也适用于Swift 3


Update: As of Swift 4, String is (again) a collection of its Character s:更新:从 Swift 4 开始, String是(再次)其Character的集合:

let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "🐶", "🐮", " ", "🇩🇪"]

Edit (Swift 4)编辑(斯威夫特 4)

In Swift 4, you don't have to use characters to use map() .在 Swift 4 中,您不必使用characters来使用map() Just do map() on String.只需在字符串上执行map()

let letters = "ABC".map { String($0) }
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 中,您可以对characters属性使用map()函数。

let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]

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

$ swift
Welcome to Swift!  Type :help for assistance.
  1> Array("ABC")
$R0: [Character] = 3 values {
  [0] = "A"
  [1] = "B"
  [2] = "C"
}

This below works for me:下面这对我有用:

let str = "ABC"
let arr = map(str) { s -> String in String(s) }

Reference for a global function map() is here: http://swifter.natecook.com/func/map/全局函数map()参考在这里: http : //swifter.natecook.com/func/map/

There is also this useful function on String: components(separatedBy: String) String 上也有这个有用的函数: components(separatedBy: String)

let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]

Works well to deal with strings separated by a character like ";"可以很好地处理由“;”等字符分隔的字符串or even "\\n"甚至 "\\n"

Updated for Swift 4为 Swift 4 更新

Here are 3 ways.这里有3种方法。

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

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.在某些情况下,人们真正想要的是一种将字符串转换为每个长度为 1 个字符的小字符串数组的方法。 Here is a super efficient way to do that:这是一个超级有效的方法:

//array of String
var strArr = myString.map { String($0)}

Swift 3斯威夫特 3

Here are 3 ways.这里有3种方法。

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

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.在某些情况下,人们真正想要的是一种将字符串转换为每个长度为 1 个字符的小字符串数组的方法。 Here is a super efficient way to do that:这是一个超级有效的方法:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.或者您可以向 String 添加扩展名。

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:然后你可以这样称呼它:

let charArr = "Cat".letterize()

An easy way to do this is to map the variable and return each Character as a String :一个简单的方法是map变量并将每个Character作为String返回:

let someText = "hello"

let array = someText.map({ String($0) }) // [String]

The output should be ["h", "e", "l", "l", "o"] .输出应该是["h", "e", "l", "l", "o"]

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 协议,您还可以枚举一个字符串,在每次迭代中获取每个字符。

let characters = "Hello"
var charactersArray: [Character] = []

for (index, character) in enumerate(characters) {
    //do something with the character at index
    charactersArray.append(character)
}

println(charactersArray)
    let string = "hell0"
    let ar = Array(string.characters)
    print(ar)

for the function on String: components(separatedBy: String)对于字符串上的函数:components(separatedBy: String)

in Swift 5.1在 Swift 5.1 中

have change to:更改为:

string.split(separator: "/")

In Swift 4, as String is a collection of Character , you need to use map在 Swift 4 中,由于StringCharacter的集合,您需要使用map

let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>

You can also create an extension:您还可以创建扩展:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}
func letterize() -> [Character] {
    return Array(self.characters)
}

Suppose you have four text fields "otpOneTxt","otpTwoTxt","otpThreeTxt","otpFourTxt" and a string "getOtp"假设您有四个文本字段“otpOneTxt”、“otpTwoTxt”、“otpThreeTxt”、“otpFourTxt”和一个字符串“getOtp”

            let getup = "5642"
            let array = self.getOtp.map({ String($0) })
            
            otpOneTxt.text = array[0] //5
           
            otpTwoTxt.text = array[1] //6
           
            otpThreeTxt.text = array[2] //4
            
            otpFourTxt.text = array[3] //2

For Swift version 5.3 its easy as:对于 Swift 5.3 版,它很简单:

let string = "Hello world"
let characters = Array(string)

print(characters)

// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"] // [“你好世界”]

let str = "cdcd"
let characterArr = str.reduce(into: [Character]()) { result, letter in
    result.append(letter)
}
print(characterArr)
//["c", "d", "c", "d"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM