This question already has answers here:
Repeating String in Swift
(8 answers)
Closed 5 months ago.
To size a view, I needed to build a string by repeating a single character. I came up with the following:
var str = ""
for _ in 0 ..< length {
str.append("W")
}
I also came up with a functional alternative:
let str = (0 ..< digits).reduce("") { (result, _) -> String in
result + "0" // assuming 0 is the most wide number
}
Both feel a bit verbose. Is there a shorter way or a built-in function in Swift?
Use init(repeating:count:)
var str = String(repeating: "w", count: length)
Related
This question already has answers here:
How do I cycle through the entire alphabet with Swift while assigning values?
(5 answers)
Closed 1 year ago.
I want to convert alphabets to numbers, in this way: a=0, b=1, c=2 ... z=25 in Swift.
I have an array of integers range 0-25. I want to get alphabets from the Int array.
If I have an array of characters, how can I get an array of Int?
//Create an array of UInt8 vaues:
var array = [UInt8]()
for _ in 1...20 {
array.append(UInt8.random(in: 0...25))
}
//Now map the array of values to characters 'a' to 'z'
let charArray = array.map {UnicodeScalar($0 + (Character("a").asciiValue ?? 0))}
charArray.forEach { print($0) }
//Now map the char array back to int values
let valueOfA = Character("a").asciiValue ?? 0
let charToUIntArray = charArray.map { (Character($0).asciiValue ?? 0) - valueOfA}
How to get string from ASCII code in Swift?
You can make your numbers match the right characters if you add an offset to your numbers and assign this number with the Character initializer to your character.
func getChar(number: Int)->Character{
return Character(UniCodeScalar(number+97))
}
The other way around you can use the asciiValue property.
(What's the simplest way to convert from a single character String to an ASCII value in Swift?)
After that you can loop through the array and use for example functions to convert.
This question already has answers here:
Concatenate Swift Array of Int to create a new Int
(5 answers)
Closed 2 years ago.
I have an [Int] array like so:
[1, 2, 3]
How can I apply a function on this so it returns:
123
?
let nums = [1, 2, 3]
let combined = nums.reduce(0) { ($0*10) + $1 }
print(combined)
Caveats
Make sure the Int won't overflow if the number gets too long (+263 on a 64-bit system).
You need to also be careful all numbers in the list aren't more than 9 (a single base-10 digit), or this arithmetic will fail. Use the String concatenation technique to ensure that all base-10 numbers are correctly handled. But, again, you need to be careful that the number won't overflow if you choose to convert it back to an Int.
We can do like below...
var finalStr = ""
[1,2,3].forEach {
finalStr.append(String($0))
}
if let number = Int(finalStr) {
print(number)
}
This question already has answers here:
Get nth character of a string in Swift
(47 answers)
Closed 3 years ago.
I am trying to extract a partial String from a given input String in Swift5. Like the letters 2 to 5 of a String.
I was sure, something as simple as inputString[2...5]would be working, but I only got it working like this:
String(input[(input.index(input.startIndex, offsetBy: 2))..<(input.index(input.endIndex, offsetBy: -3))])
... which is still using relative positions (endIndex-3 instead of position #5)
Now I am wondering where exactly I messed up.
How do people usually extract "cde" from "abcdefgh" by absolute positions??
I wrote the following extension for shorthand substrings without having to deal with indexes and casting in my main code:
extension String {
func substring(from: Int, to: Int) -> String {
let start = index(startIndex, offsetBy: from)
let end = index(start, offsetBy: to - from + 1)
return String(self[start ..< end])
}
}
let testString = "HelloWorld!"
print(testString.substring(from: 0, to: 4)) // 0 to 4 inclusive
Outputs Hello.
This question already has answers here:
Swift: How to get substring from start to last index of character
(23 answers)
Closed 4 years ago.
In swift 4 you can use the following method to extract a substring:
let str = "abcdefghci"
let index = str.index(of: "c") ?? str.endIndex
print(str[...index])
This will print abc
But how can I find the index of the last c, to extract a substring from that location ?
UPDATE
#vadian please see the attached image:
Use range(of which can search backwards and use lowerBound as end index.
let str = "abcdefghci"
if let range = str.range(of: "c", options: .backwards) {
print(str[...range.lowerBound])
}
This question already has answers here:
Swift How to get integer from string and convert it into integer
(10 answers)
Closed 6 years ago.
I receive from a server API a String like "14px". How to transform this String to Int with value 14 ignoring substring "px"?
If string always come with just px at last you can subscript it and ignore the last 2 characters.
let str = "14px"
var numStr = str.substring(to: str.index(name.endIndex, offsetBy: -2))
print(numStr) // "14"
//Now you can convert "14" to Int
print(Int(numStr))
Or
print(Int(String(str.characters.dropLast(2))))