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) 
        }
    }
}

History

  1. 2022.02.11

Last updated