Sometimes a String
needs to be a certain number of characters long. It must fill an entire text field. With padding methods, we can add characters to a String
.
In Foundation, we find a method called padding()
with 3 arguments. We specify a string
that is added to fill the desired length. This pads a string
.
To begin, we introduce a String
that has 4 characters (cats). We then invoke the padding()
method. We use 3 arguments.
string
to a width of 10 characters. The resulting string
will have 10 chars in its padded form.string
is used to create the padding. It is repeated to fill the desired length.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)|")Padded = |cats |
With the padding()
method, we can pad with different characters. A space is a common padding char
, but here we use a hyphen to pad a string
.
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)X1--
In Swift, strings can be hard to manipulate. But we usually do best by choosing the most specific Foundation method possible.
In Swift 3 we use padding()
instead of stringByPaddingToLength
. The method call is simpler, and the arguments are labeled differently.
Padding increases the length of a String
to fill a field. This can be used to ensure a string
meets a length requirement. It can be used sometimes for text justification.