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 2 days ago by avibootz
...