[英]How to convert Characters to Int in Swift 4?
I have readLine()
which gives me the character. 我有
readLine()
给我角色。 So, I have this: 所以,我有这个:
223 345 567
and so on. 223 345 567
等。 So, when I convert them to Int first thing says these are character so, I researched and found this solution and when I use this: 因此,当我将它们转换为Int时,第一件事就是说这些是字符,因此,我研究并找到了此解决方案,并在使用此方法时:
let size = readLine()
var array = [Int]()
let numbers = readLine()
for number in numbers!
{
if let integer = Int(String(number))
{
array.append(integer)
}
}
print(array)
So, when I am printing the array, I am getting these as [2,2,3,3,4,5,5,6,7]
instead of [223,345,567]
. 所以,当我打印数组时,我得到的是
[2,2,3,3,4,5,5,6,7]
而不是[223,345,567]
。 Can anyone help? 有人可以帮忙吗?
Here is the extract of new code. 这是新代码的摘录。
let numbers = readLine()
var array = [Int]()
guard let numberStrings = numbers?.components(separatedBy: " ") else{
fatalError()
}
for number in numberStrings {
if let validNumber = Int(number) {
array.append(validNumber)
}
}
print(array)
You need to split the string and find every number string and then convert them to Int
. 您需要分割字符串并找到每个数字字符串,然后将它们转换为
Int
。
let numbers = readLine()
var numberArray: [Int] = []
guard let numberStrings = numbers?.components(separatedBy: " ") else {
fatalError()
}
for number in numberStrings {
if let validNumber = Int(number) {
numberArray.append(validNumber)
}
}
for number in numbers!
This line of code extracts each character
in the string
(223 345 567)
and tries to convert it to int
. 此行代码提取
string
每个character
(223 345 567)
然后尝试将其转换为int
。 That's why it converts each valid number in string and left the spaces. 这就是为什么它会转换字符串中的每个有效数字并保留空格。 You need to first split the
string
in to array
of string
numbers then iterate through the array to convert them. 您需要先将
string
分成string
编号array
,然后遍历该数组以将其转换。
Split it, further iterate through strNumArray
and convert them to integers
拆分它,进一步遍历
strNumArray
并将它们转换为integers
var array = [Int]()
if let strNumArray = numbers?.components(separatedBy: " ") {
for number in strNumArray {
if let integer = Int(String(number)) {
array.append(integer)
}
}
}
print(array)
And in more swifty way
并且以更快的方式
var arrayInt = numbers.split(separator: " ").map{Int($0)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.