str.pad()
โฌ๏ธ ้่ฆ๏ผ Character * Int
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// 2022.02.11 / .pad() change parameter order,
// width -> _ width, align -> _ position
// remove `char` default argument
// PadAlign renamed PadPosition, case names renamed
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
extension String {
/// โญ๏ธ position for string padding
public enum PadPosition {
case end, both, start
}
/// โญ๏ธ pad string with character.
/// ```
// "abc".pad("_", 10), // _______abc
// "abc".pad("_", 10, .end) // abc_______
// "abc".pad("_", 10, .both) // ___abc____
/// ```
public func pad(
_ char: Character,
_ width: Int,
_ position: PadPosition = .start
) -> String
{
// string longer than or equal to pad places
if count >= width { return self }
// string short than pad places
let remainingPlaces = width - count
let padStr = char * remainingPlaces
let leftPad = remainingPlaces / 2
let rightPad = remainingPlaces - leftPad
switch position {
case .end : return self + padStr
case .start: return padStr + self
case .both : return (char * leftPad) + self + (char * rightPad)
}
}
}
๐ See: Logger
String extension.
History
2022.02.11
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// 2022.01.28 * (v.1) + operator `*`, .pad()
// 2022.01.30 r `String.Align` renamed to `String.PadAlign`
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโ
// โ String + .pad() โ
// โโโโโโโโโโโโโโโโโโโโโโโโโ
extension String {
/// alignment for string padding
public enum PadAlign {
case left, center, right
}
/// pad string with character
public func pad(
width : Int,
_ char: Character = " ",
align : PadAlign = .left
) -> String
{
// string longer than or equal to pad places
if count >= width { return self }
// string short than pad places
let remainingPlaces = width - count
let padStr = char * remainingPlaces
let leftPad = remainingPlaces / 2
let rightPad = remainingPlaces - leftPad
switch align {
case .left : return self + padStr
case .right : return padStr + self
case .center: return (char * leftPad) + self + (char * rightPad)
}
}
}
Last updated