Swift: Format String width -


what i'm wanting simple in c/c++, java, , many other languages. want able specify width of string, similar this:

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

this create of field width of 15 characters. i've done lot of googling. i've tried using copaquepointeras string(format:in various ways no luck. suggestions appreciated. have missed when googling.

you better 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 need '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 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -