Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Format String width

Tags:

What I'm wanting to do is very simple in C/C++, Java, and so many other languages. All I want to do is be able to specify the width of a string, similar to this:

printf("%-15s", var);

This would create of a field width of 15 characters. I've done a lot of googling. I've tried using COpaquepointeras well as String(format:in various ways with no luck. Any suggestions would be greatly appreciated. I could have missed something when googling.

like image 781
Alex Cauthen Avatar asked Jun 29 '16 14:06

Alex Cauthen


2 Answers

You can use withCString to quickly convert the string to an array of bytes (technically an UnsafePointer<Int8>):

let str = "Hello world"
let formatted = str.withCString { String(format: "%-15s", $0) }

print("'\(formatted)'")
like image 123
Code Different Avatar answered Sep 28 '22 03:09

Code Different


You are better to do it yourself

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               "

if you need something 'more general'

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)

which prints

ABC
FGH
ABCDEFGH--
--ABCDEFGH
like image 21
user3441734 Avatar answered Sep 28 '22 02:09

user3441734