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"
Related
How to convert numeric array to cell array of chars and concat with chars in one line?
Example:
I have a numeric array:
[1, 5, 12, 17]
I want to convert it to a cell array of chars and concat with the chars 'Sensor ' and get:
{'Sensor 1', 'Sensor 5', 'Sensor 12', 'Sensor 17'}
Is there a way to do this in one line?
I got for now:
nums = [1, 5, 12, 17];
cellfun(#(x) ['Sensor ' num2str(x)], num2cell(nums), 'UniformOutput', 0)
Is there a simpler or more compact way?
You could make it slightly neater using sprintf() and arrayfun() but not sure this saves you a lot:
nums = [1, 5, 12, 17];
arrayfun(#(x) {sprintf('Sensor %d',x)}, nums) % Gives a cell array of char array strings
arrayfun(#(x) sprintf("Sensor %d",x), nums) % Gives an array of string strings (version 2016b onwards)
You can also use compose() in versions of MATLAB from 2016a onwards:
compose('Sensor %d', nums) % Char array
compose("Sensor %d", nums) % String array (version 2017a onwards)
Another option, which only uses functions "Introduced before R2006a", is:
A = [1, 5, 12, 17];
B = strcat('Sensor', {' '}, strtrim(cellstr(int2str(A.'))) );
This produces a column vector - so you should transpose as needed.
A simple alternative using strings:
>> nums = [1, 5, 12, 17];
>> cellstr("Sensor " + nums)
ans =
1×4 cell array
{'Sensor 1'} {'Sensor 5'} {'Sensor 12'} {'Sensor 17'}
Strings require MATLAB R2017a.
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]
I am new to Scala and this is the first time I'm using it. I want to read in a textfile with with two columns of numbers and store each column items in a separate list or array that will have to be cast as integer. For example the textfile looks like this:
1 2
2 3
3 4
4 5
1 6
6 7
7 8
8 9
6 10
I want to separate the two columns so that each column is stored in its on list or array.
Lets say you named the file as "columns", this would be a solution:
val lines = Source.fromFile("columns").getLines()
/* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt))
/* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */
val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
/* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/
val leftList: List[Int] = pair._1.reverse
val rightList: List[Int] = pair._2.reverse
//finally you apply reverse to the lists and it's done :)
Here is one possible way of doing this:
val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)
scala> val columnsTogether = source.getLines.map { line =>
val nums = line.split(" ") // creating an array of just the 'numbers'
(nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))
scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)
scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
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) }
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