Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Is there a built-in Swift function to pad Strings at the beginning?

Writer Mia Lopez

The String function padding(toLength:withPad:startingAt:) will pad strings by adding padding characters on the end to "fill out" the string to the desired length.

Is there an equivalent function that will pad strings by prepending padding characters at the beginning?

This would be useful if you want to right-justify a substring in a monospaced output string, for example.

I could certainly write one, but I would expect there to be a built-in function, seeing as how there is already a function that pads at the end.

7

2 Answers

You can do this by reversing the string, padding at the end, end then reversing again…

let string = "abc"
// Pad at end
string.padding(toLength: 7, withPad: "X", startingAt: 0)
// "abcXXXX"
// Pad at start
String(String(string.reversed()).padding(toLength: 7, withPad: "X", startingAt: 0).reversed())
// "XXXXabc" 

Since Swift string manipulations are a rehash of the old NSString class, I suppose Apple never bothered to complete the feature set and just gave us toll free bridging as mana from the gods.

Or, since Objective-C never shied away from super verbose yet cryptic code, they expect us to use the native function twice :

let a = "42"
"".padding(toLength:10, withPad:a.padding(toLength:10, withPad:"0", startingAt:0), startingAt:a.characters.count)
// 0000000042

.

[EDIT] Objective-C ranting aside, the solution is a bit more subtle than that and adding some more useful padding methods to the String type is probably going to make things easier to use and maintain:

For example:

extension String
{ func padding(leftTo paddedLength:Int, withPad pad:String=" ", startingAt padStart:Int=0) -> String { let rightPadded = self.padding(toLength:max(count,paddedLength), withPad:pad, startingAt:padStart) return "".padding(toLength:paddedLength, withPad:rightPadded, startingAt:count % paddedLength) } func padding(rightTo paddedLength:Int, withPad pad:String=" ", startingAt padStart:Int=0) -> String { return self.padding(toLength:paddedLength, withPad:pad, startingAt:padStart) } func padding(sidesTo paddedLength:Int, withPad pad:String=" ", startingAt padStart:Int=0) -> String { let rightPadded = self.padding(toLength:max(count,paddedLength), withPad:pad, startingAt:padStart) return "".padding(toLength:paddedLength, withPad:rightPadded, startingAt:(paddedLength+count)/2 % paddedLength) }
}
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.