Swift 3: Split string into Array of Int - arrays

I'm trying to split string into Array Of integers:
let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.characters.flatMap{Int(String($0))}
But my problem is I'm getting this output:
[1, 2, 1, 0]
When I should be getting this output:
[1, 2, 10]
What I'm doing wrong?
I'll really appreciate your help.

Use this
let stringNumbers = "1 2 10"
let array = stringNumbers.components(separatedBy: " ")
let intArray = array.map { Int($0)!} // [1, 2, 10]

You are converting the individual characters of the strings into numbers. First the 1, then the space, then the 2, then the space, then the 1, and lastly the 0. If course converting the space gives a nil with is filtered out by using flatMap.
You can do:
let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.components(separatedBy: " ").flatMap { Int($0) }
This splits the original string into an array of strings (separated by a space) and then maps those into integers.

In Swift 5 it is:
let stringNumbers = "1 2 10"
var arrayIntegers = stringNumbers.split(separator: " ").compactMap { Int($0) }

Related

How can I write a method that takes in a string input and prints the first most repeated character in that string

I was trying to make a function that can iterate through any string and return the most common character within that string. My progress is shown below. I was trying to insert the character array into a dictionary where I could then print out the dictionary containing every character and their count. For the people that Think no effort was put in, I merely left out all of the code that I have tried and commented out. Didn't see any use for that so only the essentials were included.
let str = "sunday, monday, happy days"
var charStr = Array(str.characters)
var charDict = Dictionary<Character,Int>()
print("This is the character string array: " , charStr)
You can easily iterate through your characters and increase the number of occurrences of it in your dictionary:
Swift 3
let str = "sunday, monday, happy days"
var charDict: [Character: Int] = [:]
for char in str.characters {
charDict[char] = (charDict[char] ?? 0) + 1
}
print(charDict) // ["d": 3, "u": 1, "a": 4, "h": 1, ",": 2, "n": 2, " ": 3, "m": 1, "o": 1, "y": 4, "s": 2, "p": 2]
You can use max method on your character collection to get the maximum value of your dictionary
if let mostFrequent = charDict.max(by: { $0.value < $1.value }) {
let chars = charDict.filter { $0.value == mostFrequent.value }
.map { $0.key }
.sorted()
print("The most frequent characters are:", chars) // ["a", "y"]
print("Number of occurences:", mostFrequent.value) // 4
}
The most frequent character is: a
Number of occurences: 4

Convert string into array without quotation marks in Swift 3

My question:
This answer explains how to convert a String containing elements separated by spaces into an array.
let numbers = "1 2 3 4"
let numbersArray = numbers.components(separatedBy: " ")
print(numbersArray)
// output: ["1", "2", "3", "4"]
// but I want: [1, 2, 3, 4]
However, I'm trying to make an array without quotation marks, because I'm making an array of numbers, not strings.
My attempts:
I tried removing all quotation marks from numbersArray, but this didn't work as it's an array, not a string.
numbersArray.replacingOccurrences(of: "\"", with: "") // won't work
I tried something different: I tried adding each element in the array to a new array, hoping that new array wouldn't contain quotation marks. I got an error, though:
let numbers = "1 2 3 4" // string to be converted into array without quotes
let numbersArray = numbers.components(separatedBy: " ") // convert string into array with quotes
var newNumbersArray = [String]() // new blank array (which will be without quotes)
for i in numbersArray { // for each item in the array with quotes
newNumbersArray += i // (hopefully) add the item in the new array without quotes
}
print(newNumbersArray) // print the new array
This gives me an error:
Swift:: Error: cannot convert value of type '[String]' to expected argument type 'inout String'
newNumbersArray += i
You can apply a flatMap call on the [String] array resulting from the call to components(separatedBy:), applying the failable init(_:radix:) of Int in the body of the transform closure of the flatMap invokation:
let strNumbers = "1 2 3 4"
let numbersArray = strNumbers
.components(separatedBy: " ")
.flatMap { Int($0) }
print(numbersArray) // [1, 2, 3, 4]
print(type(of: numbersArray)) // Array<Int>
You can try this:
var newArray = [Int]()
for item in numbersArray{
newArray.append(Int(item))
}
print(newArray)
Swift 3.0
Try this.. Chaining method makes it easy.
let temp = "1 2 3 4 5 6"
var numbers: [Int] = []
temp.components(separatedBy: " ").forEach { numbers.append(Int($0)!) }
print(numbers) //[1, 2, 3, 4, 5, 6]

Concatenate Swift Array of Int to create a new Int

How can you make an Array<Int> ([1,2,3,4]) into a regular Int (1234)? I can get it to go the other way (splitting up an Int into individual digits), but I can't figure out how to combine the array so that the numbers make up the digits of a new number.
This will work:
let digits = [1,2,3,4]
let intValue = digits.reduce(0, combine: {$0*10 + $1})
For Swift 4+ :
let digits = [1,2,3,4]
let intValue = digits.reduce(0, {$0*10 + $1})
Or this compiles in more versions of Swift:
(Thanks to Romulo BM.)
let digits = [1,2,3,4]
let intValue = digits.reduce(0) { return $0*10 + $1 }
NOTE
This answer assumes all the Ints contained in the input array are digits -- 0...9 . Other than that, for example, if you want to convert [1,2,3,4, 56] to an Int 123456, you need other ways.
You can go through string conversion too:
Int(a.map(String.init).joined())
You could also do
let digitsArray = [2, 3, 1, 5]
if let number = Int.init(d.flatMap({"\($0)"}).joined()) {
// do whatever with <number>
}
Just another solution
let nums:[UInt] = [1, 20, 3, 4]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value)
}
This code also works if the values inside the nums array are bigger than 10.
let nums:[UInt] = [10, 20, 30, 40]
if let value = Int(nums.map(String.init).reduce("", combine: +)) {
print(value) // 10203040
}
This code required the nums array to contain only non negative integers.
let number = [1, 2, 3].reduce(0){ $0 * 10 + $1 }
print("result: \(number)") // result: 123

How to convert string of integers to int array?

How can the following string be converted into an integer array?
"1,2,3,4,5"
Xcode 8.3.1 • Swift 3.1
You can use componentsSeparatedByString method to convert your string to an array and use flatMap to convert it to Int:
let str = "1,2,3,4,5"
let arr = str.components(separatedBy: ",").flatMap{Int($0)}
print(arr) // "[1, 2, 3, 4, 5]\n"
If your string contains spaces also you can trim it using stringByTrimmingCharactersInSet before converting to Int:
let str = "1, 2, 3, 4, 5 "
let numbers = str.components(separatedBy: ",")
.flatMap{ Int($0.trimmingCharacters(in: .whitespaces)) }
print(numbers) // "[1, 2, 3, 4, 5]\n"

Convert array.count to String

I need to convert an array.count to String values for the count, i.e.
array.count = 5 should return ["0","1","2","3","4"]
I've tried
var strRow = array.map { String($0) }
return strRow
but it's not working the way it should. Any help will be appreciated.
Try
return Array(0...array.count)
if you want array of Strings, then just map it
Array(0...array.count).map{String($0)}
Try this (Hint are in the Code Comments):
var array = [1, 2, 3, 4, 5] // array.count = 5
var stringArray = [String]()
// 0 ... array.count to go from 0 to 5 included
for index in 0 ... array.count {
// append index with cast it to string
stringArray.append(String(index))
}
print(stringArray)
// result -> ["0","1","2","3","4","5"]
In your question you give an example that array of count 5 should be transformed to ["0","1","2","3","4","5"], that's a 6-count array, are you sure this is what you need? I will assume that you want 5-count array to be transformed to ["0","1","2","3","4"], please correct me in the comments if I'm wrong.
Here's the solution I propose:
let array = [5,5,5,5,5] // count 5
let stringIndices = array.indices.map(String.init)
// ["0", "1", "2", "3", "4"]

Resources