2016-05-14 146 views
1

如何使對齊到右邊的字符串?現在,我知道如何使用stringByPaddingToLength將字符串對齊到左邊。任何想法對齊到正確的?Swift如何使字符串對齊到右邊

+2

[填充的可能的複製小號特向左](http://stackoverflow.com/questions/964322/padding-string-to-left) – ozgur

+0

@ozgur我想它對齊到正確的,沒有離開。 –

+0

'stringByPaddingToLength'已經填充到右側。我分享的鏈接解釋瞭如何使用'stringByPaddingToLength'完成相反的操作*(填充到左邊)*。 – ozgur

回答

2

一種可能的實現(解釋直列):

extension String { 
    func stringByLeftPaddingToLength(newLength : Int) -> String { 
     let length = self.characters.count 
     if length < newLength { 
      // Prepend `newLength - length` space characters: 
      return String(count: newLength - length, repeatedValue: Character(" ")) + self 
     } else { 
      // Truncate to the rightmost `newLength` characters: 
      return self.substringFromIndex(startIndex.advancedBy(length - newLength)) 
     } 
    } 
} 

實例:

let s = "foo" 
let padded = s.stringByLeftPaddingToLength(6) 
print(">" + padded + "<") 
// > foo< 

更新夫特3:

extension String { 
    func stringByLeftPaddingTo(length newLength : Int) -> String { 
     let length = self.characters.count 
     if length < newLength { 
      // Prepend `newLength - length` space characters: 
      return String(repeating: " ", count: newLength - length) + self 
     } else { 
      // Truncate to the rightmost `newLength` characters: 
      return self.substring(from: self.index(endIndex, offsetBy: -newLength)) 
     } 
    } 
}