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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to wrap a string into lines of width w in Swift

1 Answer

0 votes
import Foundation

// Wrap a string into lines of maximum width `w`.
// Words are kept intact; wrapping occurs only at spaces.
func wrapText(_ text: String, width w: Int) -> [String] {
    var lines: [String] = []
    var currentLine = ""

    // Split the text into words
    let words = text.split(separator: " ")

    for word in words {
        // If the current line is empty, start it with the word
        if currentLine.isEmpty {
            currentLine = String(word)
        } else {
            // Check if adding the next word exceeds the width
            if currentLine.count + 1 + word.count <= w {
                currentLine += " " + word
            } else {
                // Push the current line and start a new one
                lines.append(currentLine)
                currentLine = String(word)
            }
        }
    }

    // Append the last line if not empty
    if !currentLine.isEmpty {
        lines.append(currentLine)
    }

    return lines
}

// Usage
let text = "Swift is a powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS."
let width = 25

let wrappedLines = wrapText(text, width: width)

// Print the wrapped lines
print("Wrapped text (width \(width)):\n")
for line in wrappedLines {
    print(line)
}



/*
run:

Wrapped text (width 25):

Swift is a powerful and
intuitive programming
language for iOS, macOS,
watchOS, and tvOS.

*/

 



answered Jul 12 by avibootz
...