我想要做的是在C/C++, Java和许多其他语言中非常简单.我想要做的就是能够指定字符串的宽度,类似于: printf("%-15s", var); 这将创建15个字符的字段宽度.我做了很多谷歌搜索.我已经尝试过使
printf("%-15s", var);
这将创建15个字符的字段宽度.我做了很多谷歌搜索.我已经尝试过使用COpaquepointeras和String(格式:以各种方式没有运气.任何建议都会非常感激.我可能在谷歌搜索时遗漏了一些东西.
你最好自己动手let str0 = "alpha" let length = 20 // right justify var str20r = String(count: (length - str0.characters.count), repeatedValue: Character(" ")) str20r.appendContentsOf(str0) // " alpha" // left justify var str20l = str0 str20l.appendContentsOf(String(count: (length - str0.characters.count), repeatedValue: Character(" "))) // "alpha "
如果你需要更“一般”的东西
func formatString(str: String, fixLenght: Int, spacer: Character = Character(" "), justifyToTheRigth: Bool = false)->String { let c = str.characters.count let start = str.characters.startIndex let end = str.characters.endIndex var str = str if c > fixLenght { switch justifyToTheRigth { case true: let range = start.advancedBy(c - fixLenght)..<end return String(str.characters[range]) case false: let range = start..<end.advancedBy(fixLenght - c) return String(str.characters[range]) } } else { var extraSpace = String(count: fixLenght - c, repeatedValue: spacer) if justifyToTheRigth { extraSpace.appendContentsOf(str) return extraSpace } else { str.appendContentsOf(extraSpace) return str } } } let str = "ABCDEFGH" let s0 = formatString(str, fixLenght: 3) let s1 = formatString(str, fixLenght: 3, justifyToTheRigth: true) let s2 = formatString(str, fixLenght: 10, spacer: Character("-")) let s3 = formatString(str, fixLenght: 10, spacer: Character("-"), justifyToTheRigth: true) print(s0) print(s1) print(s2) print(s3)
打印
ABC FGH ABCDEFGH-- --ABCDEFGH