Padding a Swift String for Printing

Padding a swift String for printing

For Swift >= 3

line += string.padding(toLength: 40, withPad: " ", startingAt: 0)

For Swift < 3

NSString has the stringByPaddingToLength: method:

line += string.stringByPaddingToLength(40, withString: " ", startingAtIndex: 0)

Leading zeros for Int in Swift

Assuming you want a field length of 2 with leading zeros you'd do this:

import Foundation

for myInt in 1 ... 3 {
print(String(format: "%02d", myInt))
}

output:

01
02
03

This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit.


The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this:

let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

output:

03:15:07

Swift formatting a string to a certain length

There is a much better, Swift-like solution:

String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0)

name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0)

String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)

According to Apple documentation:

Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.

So that's what you need.

The usage can be something as this:

let output = String(qty).stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) + name.stringByPaddingToLength(30, withString: " ", startingAtIndex: 0) + String(price).stringByPaddingToLength(8, withString: " ", startingAtIndex: 0)

UPDATE:

In order to pad to the right:

let p = String(price)
"".stringByPaddingToLength(8 - p.characters.count, withString: " ", startingAtIndex: 0) + p

C string padding to separate two strings to fixed width

int array[] = { 1, 2, 3, 4, 5, 6, 7, 42, 999 };
enum { NUM_ARRAY = sizeof( array ) / sizeof( array[ 0 ] ) };
for ( int i = 0; i < NUM_ARRAY; ++i ){
printf( "%-3d: sometext\n", array[ i ] );
}

This is a for-loop through an array. Every array-item will be printed with a padding of three.

Output:

1  : sometext
2 : sometext
3 : sometext
4 : sometext
5 : sometext
6 : sometext
7 : sometext
42 : sometext
999: sometext

How can I format string with fixed length in swift

Basically, to format String with String(format: _:...), we can use %@:

String(format: "%@ - %@", "key", "value")

But, I believe %@ does not support "width" modifier: you cannot %12@ or such.

So, you have to convert String to COpaquePointer which can be formatted with %s:

var key = "key"
var val = "value"

var str = String(format: "%-12s - %s",
COpaquePointer(key.cStringUsingEncoding(NSUTF8StringEncoding)!),
COpaquePointer(val.cStringUsingEncoding(NSUTF8StringEncoding)!)
)
// -> "key - value"

Left and right padding (not leading and trailing) in SwiftUI

Use @Environment(\.layoutDirection) to get the current layout direction (LTR or RTL) and use it to flip .leading and .trailing as needed.

Here’s a ViewModifier that wraps all that conveniently:

enum NoFlipEdge {
case left, right
}

struct NoFlipPadding: ViewModifier {
let edge: NoFlipEdge
let length: CGFloat?
@Environment(\.layoutDirection) var layoutDirection

private var computedEdge: Edge.Set {
if layoutDirection == .rightToLeft {
return edge == .left ? .trailing : .leading
} else {
return edge == .left ? .leading : .trailing
}
}

func body(content: Content) -> some View {
content
.padding(computedEdge, length)
}
}

extension View {
func padding(_ edge: NoFlipEdge, _ length: CGFloat? = nil) -> some View {
self.modifier(NoFlipPadding(edge: edge, length: length))
}
}

Use it like you would the standard padding modifiers:

Text("Text")
.padding(.left, 10)


Related Topics



Leave a reply



Submit