Home
Swift
String padding Example
Updated Aug 23, 2023
Dot Net Perls
Padding. 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.
First example. To begin, we introduce a String that has 4 characters (cats). We then invoke the padding() method. We use 3 arguments.
Info We pass 10 to expand the string to a width of 10 characters. The resulting string will have 10 chars in its padded form.
And This 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 |
Different characters. 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--
Some notes. In Swift, strings can be hard to manipulate. But we usually do best by choosing the most specific Foundation method possible.
And We could apply padding by adding space chars, but this is more complex. A single Foundation call is clearer.
Swift 3 changes. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen