如何与“\ t”对齐 - 右对齐或左对齐?

时间:2016-03-18 01:53:07

标签: ios swift

我正在尝试列出姓名,出生日期和年龄。我想以一个整洁的显示打印出每个名字,DOB和年龄。例如:

names = ["name112312", "name2123", "name3as"]
dob = ["jan112", "dec9", "augasd5"]
age = [1, 2, 123]

我打算打印出来的是:

Name         DOB         Age

name112312   jan112       1

name2123     dec9         26

name3as      augasd5      123

注意每个名称的对齐方式,即使名称的长度不同。

这就是我要做的,这就是目前正在发生的事情:

http://i.stack.imgur.com/gMbVI.png

代码:

var list_DbU: Int

var db_nameS : Array = ["Bill", "Joe", "Sam", "Cathy"]
var db_dobS : Array = ["08:02:00", "01:25:96", "12:24:01", "04:03:99"]
var db_ageS : Array = [15, 19, 14, 16]


println("Db info: ")
println("Name \t DOB \t Age")
for list_DbU = 0; list_DbU < db_nameS.count; ++list_DbU {
    println("\n\(db_nameS[list_DbU]) \t \(db_dobS[list_DbU])")
}

1 个答案:

答案 0 :(得分:1)

使用NSString(format:)可以填充宽度,%-20s20是您的字段的宽度

var list_DbU: Int

var db_nameS : Array = ["Bill", "Joe", "Sam", "Cathy"]

    var db_dobS : Array = ["08:02:00", "01:25:96", "12:24:01", "04:03:99"]
    var db_ageS : Array = [15, 19, 14, 16]

    print("Db info: ")
    print(NSString(format: "%-20s%-20s%-20s", ("Name" as NSString).UTF8String, ("DOB" as NSString).UTF8String , ("Age" as NSString).UTF8String))
    for list_DbU = 0; list_DbU < db_nameS.count; ++list_DbU {
        let name = (db_nameS[list_DbU] as NSString).UTF8String
        var dob = (db_dobS[list_DbU] as NSString).UTF8String
        var age = db_ageS[list_DbU]
        print(NSString(format: "%-20s%-20s%d", name, dob, age))
    }

输出:

Db info: 
Name                DOB                 Age                 
Bill                08:02:00            15
Joe                 01:25:96            19
Sam                 12:24:01            14
Cathy               04:03:99            16