Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

How to format a string using fixed-width fields in Swift

11 Answers

0 votes
/*
Common format specifiers
-----------------------------------
%-10s // Left-aligned string, width 10
%10s // Right-aligned string, width 10
%5d // Integer, width 5
%08d // Integer, width 8, padded with zeros
%12.2f // Floating-point, width 12, 2 decimal places
*/

import Foundation

/// Formats a record using fixed-width fields.
///
/// %-15s = left-aligned string, width 15
/// %10d  = right-aligned integer, width 10
/// %12.2f = right-aligned floating-point number,
///           width 12, 2 decimal places
func formatRecord(name: String, age: Int, salary: Double) -> String {
    let nameField = name.padding(
        toLength: 15,
        withPad: " ",
        startingAt: 0
    )

    let ageField = String(format: "%10d", age)
    let salaryField = String(format: "%12.2f", salary)

    return nameField + ageField + salaryField
}

// Store the formatted string in a variable
let result = formatRecord(
    name: "Jean",
    age: 71,
    salary: 210000.0
)

print(result)


/*
run:

Jean                   71   210000.00

*/

 



answered 3 days ago by avibootz
edited 3 days ago by avibootz
0 votes
import Foundation

let result = "Hello".withCString { cString in
    String(format: "%-10s", cString)
}

print("|\(result)|")


/*
run:

|Hello     |

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

let result = "Hello".padding(
    toLength: 10,
    withPad: " ",
    startingAt: 0
)

print("|\(result)|")


/*
run:

|Hello     |

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

// Right-align "Nicola" in a field 11 characters wide

let result = "Nicola".withCString { cString in
    String(format: "%11s", cString)
}

print("|\(result)|")


/*
run:

|     Nicola|

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

// Right-align "Nicola" in a field 11 characters wide

let result = String(repeating: " ", count: max(0, 11 - "Nicola".count)) + "Nicola"

print("|\(result)|")


/*
run:

|     Nicola|

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

extension String {
    func rightAligned(width: Int) -> String {
        String(repeating: " ", count: max(0, width - count)) + self
    }
}

let result = "Nicola".rightAligned(width: 11)

print("|\(result)|")


/*
run:

|     Nicola|

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation
 
// Zero-padding numbers
 
let number = 42

// Format the number as a 5-digit string.
// %d = integer
// 5  = minimum width
// 0  = pad with zeros on the left
let paddedNumber = String(format: "%05d", number)

print(paddedNumber) // 00042
 
 
/*
run:
 
00042
 
*/

 



answered 3 days ago by avibootz
edited 3 days ago by avibootz
0 votes
import Foundation

// Helper function to left-align text in a fixed-width field
func pad(_ text: String, width: Int) -> String {
    return text.padding(
        toLength: width,
        withPad: " ",
        startingAt: 0
    )
}

// Print column headers
print(
    pad("Name", width: 15) +
    pad("Age", width: 10) +
    pad("Salary", width: 12)
)

// Print data rows
print(
    pad("Nicola", width: 15) +
    String(format: "%-10d", 45) +
    String(format: "%-12.2f", 105000.0)
)

print(
    pad("Luna", width: 15) +
    String(format: "%-10d", 56) +
    String(format: "%-12.2f", 162000.0)
)


/*
run:

Name           Age       Salary      
Nicola         45        105000.00   
Luna           56        162000.00   

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

/// Returns a string padded to a fixed width.
///
/// Parameters:
///   - value: The value to format.
///   - width: The field width.
///   - leftAlign: true for left alignment,
///                false for right alignment.
func fixedWidth(
    _ value: String,
    width: Int,
    leftAlign: Bool = true
) -> String {

    if value.count >= width {
        return value
    }

    let padding = String(
        repeating: " ",
        count: width - value.count
    )

    return leftAlign
        ? value + padding
        : padding + value
}

print("|\(fixedWidth("Hello", width: 10))|")
print("|\(fixedWidth("123", width: 10, leftAlign: false))|")


/*
run:

|Hello     |
|       123|

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation

/// Returns a string padded to a fixed width.
///
/// Parameters:
///   - value: The value to format.
///   - width: The field width.
///   - leftAlign: true for left alignment,
///                false for right alignment.

// If you specifically want to keep using String(format:), 
// convert the Swift string to a C string:
func fixedWidth(
    _ value: String,
    width: Int,
    leftAlign: Bool = true
) -> String {

    return value.withCString { cString in
        if leftAlign {
            return String(format: "%-\(width)s", cString)
        } else {
            return String(format: "%\(width)s", cString)
        }
    }
}

print("|\(fixedWidth("Hello", width: 10))|")
print("|\(fixedWidth("123", width: 10, leftAlign: false))|")


/*
run:

|Hello     |
|       123|

*/

 



answered 3 days ago by avibootz
0 votes
import Foundation
 
// Zero-padding numbers
 
let number = 42
let width = 8

// Pad the number with leading zeros up to the specified width
let paddedNumber = String(format: "%0*d", width, number)

print(paddedNumber) // 00000042
 
 
/*
run:
 
00000042
 
*/

 



answered 3 days ago by avibootz
...