I have a series of string that I need to print on 1 line.
var qty: Int = 1
var name: "Book"
var price: 13.50
I need each to have blank space appended to them so they are a certain length or have characters removed if they are too long. For the qty id like it to be a length of 3, name 30 and price 8
Format should be
1 Book 13.50
There is a much better, Swift-like solution:
String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0)
name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0)
String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)
According to Apple documentation:
Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.
So that's what you need.
The usage can be something as this:
let output = String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) + name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0) + String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)
UPDATE:
In order to pad to the right:
let p = String(price)
"".stringByPaddingToLength(8 - p.characters.count, withString: " ", startingAtIndex: 0) + p
Related
I'm trying to achieve string truncate with "& more..." when string is truncated. I have this in picture:
Exact code minus text, in image:
func formatString() -> String {
let combinedLength = 30
// This array will never be empty
let strings = ["Update my profile", "Delete me", "Approve these letters"]
// In most cases, during a loop (no order of strings)
//let strings = ["Update", "Delete", "Another long word"]
let rangeNum = strings.count > 1 ? 2 : 1
let firstN = strings[0..<rangeNum]
// A sum of first 2 or 1
let actualLength = firstN.compactMap { $0.count }.reduce(0, +)
switch actualLength {
case let x where x <= combinedLength:
// It's safe to display all
return strings.map{String($0)}.joined(separator: ", ")
default:
if rangeNum == 2 {
if actualLength <= combinedLength {
return strings.first! + ", " + strings[1] + ", & \(strings.count - 2) more..."
}
return strings.first! + ", & \(strings.count - 1) more..."
}
// There has to be at least one item in the array.
return strings.first!
}
}
While truncateMode looks like a match, it's missing the , & n more... where n is the remainder.
My code may not be perfect but was wondering how to refactor. I feel there's a bug in there somewhere. I've not taken into consideration for larger screens: iPad where I would want to display more comma-separated values, I only look for the max 2 then display "& n more" depending on the size of the array.
Is there a hidden modifier for this? I'm using XCode 13.4.1, targeting both iPhone and iPad.
Edit:
The title is incorrect. I want to convert an array of strings into a comma-separated value string that's truncated using the function I have.
I want to divide difference data into 60 and print it as double numbers. When I print it as a string, it does not appear to be a fraction of the number. I get this problem when I print the number "n" . What should I do?
My mistake: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
if let date = formatter.date(from: receivedTimeString) {
let receivedTimeHoursMinutes = Calendar.current.component(.hour, from: date) * 60
let receivedTimeMinutes = Calendar.current.component(.minute, from: date)
let totalreceivedTimeMinutes = receivedTimeHoursMinutes + receivedTimeMinutes
let todayHoursMinutes = Calendar.current.component(.hour, from: Date()) * 60
let todayMinutes = Calendar.current.component(.minute, from: Date())
let todayTimeMinutes = todayHoursMinutes + todayMinutes
let difference = todayTimeMinutes - totalreceivedTimeMinutes
let str = String(difference)
switch true {
case difference > 60:
let deger = String(difference / 60)
guard let n = NumberFormatter().number(from: deger) else { return }
print("deger", deger)
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Saattir") + (" ") + (durum)
case difference == 0:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
case difference < 60:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
default:
self.labelTimerFarkSonuc.text = (n) + (" ") + ("Dakikadır") + (" ") + (durum)
}
If i had understood your question correctly,
If you want to have result of following code as decimal fraction,
let deger = String(difference / 60) // Dividing by INT will not give fractions.
Change it to following.
let deger = String(difference / 60.0)
junior developer here. I am currently trying to achieve a substring that is split every n characters of a String.
This is my code for the function
public func split(every: Int) -> [String] {
var result = [String]()
for i in stride(from: 0, to: self.count, by: every) {
let startIndex = self.index(self.startIndex, offsetBy: i)
let endIndex = self.index(startIndex, offsetBy: every, limitedBy: self.endIndex) ?? self.endIndex
result.append(String(self[startIndex..<endIndex]))
}
return result
}
The above code works as expected. But there is one lacking from the code above, which is the word wrapping. Here is the sample String
let itemName = "Japanese Matcha SM w RB -L Special Edition And Americano MS w Brown Sugar Limited Edition"
print(itemName.split(every: 26))
The result will be
["Japanese Matcha SM w RB -L", " Special Edition And Ameri", "cano MS w Brown Sugar Limi", "ted Edition"]
Notice the
[" Special Edition And Ameri"], ["cano MS w Brown Sugar Limi"]
I am trying to figure out how to do the word wrap algorithm based on every n character, but couldn't find any clue.
For example, from above case, how to generate the array becomes,
[" Special Edition And"], ["Americano MS w Brown"], ["Sugar"]
So as you can see, the algorithm might check whether every n characters has a word that is being cut out (dynamic check based on the n characters), hence will move the cut word into the next array.
So in that case, the algorithm will cleverly bypass the every n character, might be less, but not more than n characters, if there is any word not being wrapped.
Is my explanation clear? Can anyone guide me please? Thanks
This is some simple implementation of this algorithm, you can start with that.
First we cut string by words, then add them to temporary string until we meet characters limit.
let itemName = "Japanese Matcha SM w RB -L Special Edition And Americano MS w Brown Sugar Limited Edition"
let table = itemName.split(separator: " ")
let limit = 26
var tempString = ""
var finalResult: [String] = []
for item in table {
tempString += item + " "
if tempString.count >= limit {
finalResult.append(tempString)
tempString = ""
}
}
print(finalResult)
How about this?
extension String {
func split(every: Int) -> [String] {
var result = [String]()
let words = self.split(separator: " ")
var line = String(words.first!)
words.dropFirst().forEach { word in
let word = " " + String(word)
if line.count + word.count <= every {
line.append(word)
} else {
result.append(line)
line = word
}
}
result.append(line)
return result
}
}
Hi guys I have a probelm that I needed to solve. Here are the examples:
input is ABCD12345 will output ABCD 12345
input is A12345BCDE will output A 12345 BCDE
imput is ABC 12345 will output ABC 12345 (excess spacing removed)
As shown above a single spacing shall be added when there are no spacing but if there is, it will check if there are double spaces, then it will make it into single spacing.
To accomplish what you ask you can do something like this:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var res = ""
var lastDigit = false
for char in [input].unicodeScalars {
if letters.longCharacterIsMember(char.value) && lastDigit {
res += " "
lastDigit = false
} else if digits.longCharacterIsMember(char.value) && !lastDigit {
res += " "
lastDigit = true
}
if String(char) != " " {
res += String(char)
}
}
print(res)
In the code above you should replace the [input] placeholder with the input that you want to deal and the result string will be in res variable.
Like this Java question, but for Swift.
How can I output a table like this to the console, ideally using println?
n result1 result2 time1 time2
-----------------------------------------------------
5 1000.00 20000.0 1000ms 1250ms
5 1000.00 20000.0 1000ms 1250ms
5 1000.00 20000.0 1000ms 1250ms
I tried using println("n\tresult1\tresult2") but the results don't line up properly.
I found a quick and easy way to generate columnar text output in Swift (3.0) using the String method "padding(::)" [In Swift 2.x, the method is named "stringByPaddingToLength(::)"]. It allows you to specify the width of your column, the text you want to use as a pad, and the index of the pad to start with. Works like a charm if you don't mind that it only works with left-aligned text columns. If you want other alignments, you have to buy into the other methods of character counting and other such complexities.
The solution below is contrived to illustrate the utility of the method "padding(::)". Obviously, the best way to leverage this would be to create a function that iterated through a collection to produce the desired table while minimizing code repetition. I did it this way to focus on the task at hand.
Lastly, "println" doesn't seem to exist in Swift 2.x+, so I reverted to "print()".
To illustrate an example using your stated problem:
//Set up the data
let n : Int = 5
let result1 = 1000.0
let result2 = 20000.0
let time1 = "1000ms"
let time2 = "1250ms"
//Establish column widths
let column1PadLength = 8
let columnDefaultPadLength = 12
//Define the header string
let headerString = "n".padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + "result1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "result2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Define the line separator
let lineString = "".padding(toLength: headerString.characters.count, withPad: "-", startingAt: 0)
//Define the string to display a line of our data
let nString = String(n)
let result1String = String(result1)
let result2String = String(result2)
let dataString = nString.padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + result1String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + result2String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time1.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time2.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Print out the data table
print("\(headerString)\n\(lineString)\n\(dataString)")
The output will be printed to your console in a tidy columnar format:
n result1 result2 time1 time2
--------------------------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Changing the variable "columnDefaultPadLength" from 12 to 8 will result in the following output:
n result1 result2 time1 time2
----------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Finally, reducing the padding length to a value less than the data truncates the data instead of generating errors, very handy! Changing the "columnDefaultPadLength" from 8 to 4 results in this output:
n resuresutimetime
------------------------
5 1000200010001250
Obviously not a desired format, but with the simple adjustment of the padding length, you can quickly tweak the table into a compact yet readable form.
You need to determine the maximum length of a string in your data (from both the keys and values) and then pad those strings. You can use a function like what I've provided below to calculate the maximum length and go from there.
func maxLength(data: Dictionary<String,Double>) -> Int {
var greatestLength = 0
for (key, value) in data {
var valueLength = countElements(String(format: "%.2f", value))
var keyLength = countElements(key)
var length = max(valueLength, keyLength)
if (length > greatestLength) {
greatestLength = length
}
}
return greatestLength
}