Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

swift

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.

like image 322
Duncan C Avatar asked Feb 12 '17 19:02

Duncan C


People also ask

What are string padding functions?

The Padding String function returns a padding string of the specified length and characters. Padding strings are used in alignment functions. Parameter: number. The total length to make the padding string. This can come from a source node, the result of another function, or a value you specify.

How do you slice a string in Swift?

In Swift 4 you slice a string into a substring using subscripting. The use of substring(from:) , substring(to:) and substring(with:) are all deprecated.

What is Swiftui string?

A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.


1 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"    
like image 111
Ashley Mills Avatar answered Sep 18 '22 06:09

Ashley Mills