Convert string into array without quotation marks in Swift 3 - arrays

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]

Related

String.init(stringInterpolation:) with an array of strings

I was reading over some resources about Swift 5's String Interpolation and was trying it out in a Playground. I successfully combined two separate Strings but I am confused about how to combine an Array of Strings.
Here's what I did ...
String(stringInterpolation: {
let name = String()
var combo = String.StringInterpolation(literalCapacity: 7, interpolationCount: 1)
combo.appendLiteral("Sting One, ")
combo.appendInterpolation(name)
combo.appendLiteral("String Two")
print(combo)
return combo
}())
How would you do something like this with an Array of Strings?
It’s unclear what this is supposed to have to do with interpolation. Perhaps there’s a misunderstanding of what string interpolation is? If the goal is to join an array of strings into a single comma-separated string, just go ahead and join the array of strings into a single string:
let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s // "Manny, Moe, Jack”
If the point is that the array element type is unknown but is string-representable, map thru String(describing:) as you go:
let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s // "1, 2, 3”

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

Swift 3: Split string into Array of Int

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) }

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"]

Populate Array with a set of Strings from a for-in loop for Swift

I am kinda stumped on figuring this out. I want to populate an array with the string values that comes from a for-in loop.
Here's an example.
let names = ["Anna", "Alex", "Brian", "Jack"]
for x in names {
println(x)
}
The current x value would generate 4 string values (Anna, Alex, Brian, Jack).
However I need some advice in going about getting these four values back into an array. Thank you in advance.
Whatever is on the right side of a for - in expression must be a SequenceType. Array, as it happens, can be initialised with any SequenceType. So if you're just doing something like this:
var newArray: [String] = []
for value in exoticSequence {
newArray.append(value)
}
The same thing can be accomplished (faster), by doing this:
let newArray = Array(exoticSequence)
And it doesn't matter what type exoticSequence is: if the for-in loop worked, Array() will work.
However, if you're applying some kind of transformation to your exoticSequence, or you need some kind of side effect, .map() might be the way to go. .map() over any SequenceType can return an array. Again, this is faster, and more clear:
let exoticSequence = [1, 2, 3]
let newArray = exoticSequence.map {
value -> Int in
// You can put whatever would have been in your for-in loop here
print(value)
// In a way, the return statement will replace the append function
let whatYouWouldHaveAppended = value * 2
return whatYouWouldHaveAppended
}
newArray // [2, 4, 6]
And it's equivalent to:
let exoticSequence = [1, 2, 3]
var newArray: [Int] = []
for value in exoticSequence {
print(value)
let whatYouWouldHaveAppended = value * 2
newArray.append(whatYouWouldHaveAppended)
}
newArray // [2, 4, 6]

Resources