C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ToLength: We pass 10 to expand the string to a width of 10 characters. The resulting string will have 10 chars in its padded form.
WithString: This string is used to create the padding. It is repeated to fill the desired length.
Swift program that uses padding on string
import Foundation
// An example string.
let cats = "cats"
// Pad to length 10.
let padded = cats.padding(toLength: 10, withPad: " ", startingAt: 0)
// Write result.
print("Padded = |\(padded)|")
// Print before and after lengths.
print(cats.endIndex)
print(padded.endIndex)
Output
Padded = |cats |
Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 0)
Index(_base: Swift.String.UnicodeScalarView.Index(_position: 10), _countUTF16: 0)
Swift program that pads with hyphen character
import Foundation
// A string.
let id = "X1"
// Pad with hyphens.
let padded = id.padding(toLength: 4, withPad: "-", startingAt: 0)
// Uses hyphen as padding character.
print(padded)
Output
X1--
And: We could apply padding by adding space chars, but this is more complex. A single Foundation call is clearer.