如何在Swift中转换Int数组中的字符串(数字)

时间:2022-09-11 13:42:03

I'd like to know how can I convert a String in an Int array in Swift. In Java I've always done it like this:

我想知道如何用Swift在Int数组中转换字符串。在Java中,我总是这样做:

String myString = "123456789";
int[] myArray = new int[myString.lenght()];
for(int i=0;i<myArray.lenght;i++){
   myArray[i] = Integer.parseInt(myString.charAt(i));
}  

Thanks everyone for helping!

谢谢大家帮助!

7 个解决方案

#1


16  

let str = "123456789"
let intArray = map(str) { String($0).toInt() ?? 0 }
  • map() iterates Characters in str
  • map()迭代str中的字符
  • String($0) converts Character to String
  • 字符串($0)将字符转换为字符串
  • .toInt() converts String to Int. If failed(??), use 0.
  • . toint()将字符串转换为Int. If failed(?),则使用0。

If you prefer for loop, try:

如果你喜欢for循环,可以尝试:

let str = "123456789"
var intArray: [Int] = []

for chr in str {
    intArray.append(String(chr).toInt() ?? 0)
}

OR, if you want to iterate indices of the String:

或者,如果要迭代字符串的索引:

let str = "123456789"
var intArray: [Int] = []

for i in indices(str) {
    intArray.append(String(str[i]).toInt() ?? 0)
}

#2


7  

You can use flatMap to convert the characters into a string and coerce the character strings into an integer:

可以使用flatMap将字符转换为字符串,并将字符字符串强制为整数:

Swift 2 or 3

斯威夫特2或3

let string = "123456789"
let digits = string.characters.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4

斯威夫特4

let string = "123456789"
let digits = string.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4.1

斯威夫特4.1

let digits = string.compactMap{Int(String($0))}

#3


1  

@rintaro's answer is correct, but I just wanted to add that you can use reduce to weed out any characters that can't be converted to an Int, and even display a warning message if that happens:

@rintaro的答案是正确的,但我只是想补充一点,你可以使用reduce来删除任何不能转换为Int的字符,如果发生这种情况,甚至可以显示一条警告消息:

let str = "123456789"
let intArray = reduce(str, [Int]()) { (var array: [Int], char: Character) -> [Int] in
    if let i = String(char).toInt() {
        array.append(i)
    } else {
        println("Warning: could not convert character \(char) to an integer")
    }
    return array
}

The advantages are:

优点是:

  • if intArray contains zeros you will know that there was a 0 in str, and not some other character that turned into a zero
  • 如果intArray包含0,你就会知道在str中有一个0,而不是其他字符变成了0。
  • you will get told if there is a non-Int character that is possibly screwing things up.
  • 如果有一个非int型的角色可能会把事情搞砸,你会被告知。

#4


0  

var myString = "123456789"
var myArray:[Int] = []

for index in 0..<countElements(myString) {
    var myChar = myString[advance(myString.startIndex, index)]
    myArray.append(String(myChar).toInt()!)
}

println(myArray)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

To get the iterator pointing to a char from the string you can use advance

要从字符串中获取指向char的迭代器,可以使用advance

The method to convert string to int in Swift is toInt()

在Swift中将字符串转换为int()的方法是toInt()

#5


0  

Swift 3 update:

斯威夫特3更新:

@appzYourLife : That's correct toInt() method is no longer available for String in Swift 3. As an alternative what you can do is :

@appzYourLife:正确的toInt()方法在Swift 3中不再可用。作为一种选择,你可以做的是:

intArray.append(Int(String(chr)) ?? 0)

Enclosing it within Int() converts it to Int.

将其封装在Int()中,将其转换为Int。

#6


0  

Swift 3

斯威夫特3

Int array to String

Int数组字符串

let arjun = [1,32,45,5]
    print(self.get_numbers(array: arjun))

 func get_numbers(array:[Int]) -> String {
        let stringArray = array.flatMap { String(describing: $0) }
        return stringArray.joined(separator: ",")

String to Int Array

字符串Int数组

let arjun = "1,32,45,5"
    print(self.get_numbers(stringtext: arjun))

    func get_numbers(stringtext:String) -> [Int] {
    let StringRecordedArr = stringtext.components(separatedBy: ",")
    return StringRecordedArr.map { Int($0)!}   
}

#7


0  

Swift 3: Functional Approach

  1. Split the String into separate String instances using: components(separatedBy separator: String) -> [String]
  2. 使用:component(由分隔符分隔的:String) -> [String]将字符串分割为单独的字符串实例

Reference: Returns an array containing substrings from the String that have been divided by a given separator.

引用:返回一个数组,该数组包含由给定分隔符分割的字符串中的子字符串。

  1. Use the flatMap Array method to bypass the nil coalescing while converting to Int
  2. 使用平面映射数组方法在转换为Int时绕过nil合并

Reference: Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

引用:返回一个数组,该数组包含调用给定转换的非nil结果,其中包含该序列的每个元素。

Implementation

实现

let string = "123456789"
let intArray = string.components(separatedBy: "").flatMap { Int($0) }

#1


16  

let str = "123456789"
let intArray = map(str) { String($0).toInt() ?? 0 }
  • map() iterates Characters in str
  • map()迭代str中的字符
  • String($0) converts Character to String
  • 字符串($0)将字符转换为字符串
  • .toInt() converts String to Int. If failed(??), use 0.
  • . toint()将字符串转换为Int. If failed(?),则使用0。

If you prefer for loop, try:

如果你喜欢for循环,可以尝试:

let str = "123456789"
var intArray: [Int] = []

for chr in str {
    intArray.append(String(chr).toInt() ?? 0)
}

OR, if you want to iterate indices of the String:

或者,如果要迭代字符串的索引:

let str = "123456789"
var intArray: [Int] = []

for i in indices(str) {
    intArray.append(String(str[i]).toInt() ?? 0)
}

#2


7  

You can use flatMap to convert the characters into a string and coerce the character strings into an integer:

可以使用flatMap将字符转换为字符串,并将字符字符串强制为整数:

Swift 2 or 3

斯威夫特2或3

let string = "123456789"
let digits = string.characters.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4

斯威夫特4

let string = "123456789"
let digits = string.flatMap{Int(String($0))}
print(digits)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

Swift 4.1

斯威夫特4.1

let digits = string.compactMap{Int(String($0))}

#3


1  

@rintaro's answer is correct, but I just wanted to add that you can use reduce to weed out any characters that can't be converted to an Int, and even display a warning message if that happens:

@rintaro的答案是正确的,但我只是想补充一点,你可以使用reduce来删除任何不能转换为Int的字符,如果发生这种情况,甚至可以显示一条警告消息:

let str = "123456789"
let intArray = reduce(str, [Int]()) { (var array: [Int], char: Character) -> [Int] in
    if let i = String(char).toInt() {
        array.append(i)
    } else {
        println("Warning: could not convert character \(char) to an integer")
    }
    return array
}

The advantages are:

优点是:

  • if intArray contains zeros you will know that there was a 0 in str, and not some other character that turned into a zero
  • 如果intArray包含0,你就会知道在str中有一个0,而不是其他字符变成了0。
  • you will get told if there is a non-Int character that is possibly screwing things up.
  • 如果有一个非int型的角色可能会把事情搞砸,你会被告知。

#4


0  

var myString = "123456789"
var myArray:[Int] = []

for index in 0..<countElements(myString) {
    var myChar = myString[advance(myString.startIndex, index)]
    myArray.append(String(myChar).toInt()!)
}

println(myArray)   // [1, 2, 3, 4, 5, 6, 7, 8, 9]"

To get the iterator pointing to a char from the string you can use advance

要从字符串中获取指向char的迭代器,可以使用advance

The method to convert string to int in Swift is toInt()

在Swift中将字符串转换为int()的方法是toInt()

#5


0  

Swift 3 update:

斯威夫特3更新:

@appzYourLife : That's correct toInt() method is no longer available for String in Swift 3. As an alternative what you can do is :

@appzYourLife:正确的toInt()方法在Swift 3中不再可用。作为一种选择,你可以做的是:

intArray.append(Int(String(chr)) ?? 0)

Enclosing it within Int() converts it to Int.

将其封装在Int()中,将其转换为Int。

#6


0  

Swift 3

斯威夫特3

Int array to String

Int数组字符串

let arjun = [1,32,45,5]
    print(self.get_numbers(array: arjun))

 func get_numbers(array:[Int]) -> String {
        let stringArray = array.flatMap { String(describing: $0) }
        return stringArray.joined(separator: ",")

String to Int Array

字符串Int数组

let arjun = "1,32,45,5"
    print(self.get_numbers(stringtext: arjun))

    func get_numbers(stringtext:String) -> [Int] {
    let StringRecordedArr = stringtext.components(separatedBy: ",")
    return StringRecordedArr.map { Int($0)!}   
}

#7


0  

Swift 3: Functional Approach

  1. Split the String into separate String instances using: components(separatedBy separator: String) -> [String]
  2. 使用:component(由分隔符分隔的:String) -> [String]将字符串分割为单独的字符串实例

Reference: Returns an array containing substrings from the String that have been divided by a given separator.

引用:返回一个数组,该数组包含由给定分隔符分割的字符串中的子字符串。

  1. Use the flatMap Array method to bypass the nil coalescing while converting to Int
  2. 使用平面映射数组方法在转换为Int时绕过nil合并

Reference: Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

引用:返回一个数组,该数组包含调用给定转换的非nil结果,其中包含该序列的每个元素。

Implementation

实现

let string = "123456789"
let intArray = string.components(separatedBy: "").flatMap { Int($0) }