Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func tokenizer() {
- let initialStringToSend = "TranscribeGlass shows closed captions from any source in your field of view veryveryveryveryveryverylonglongword"
- let characterPerLine = 18
- func wrap(text: String, with maximumCharacterPerLine: Int) -> [String] {
- let components = text.components(separatedBy: .whitespacesAndNewlines)
- let output = components.reduce(into: [String]()) { result, word in
- guard let last = result.last else {
- result.append(word)
- return
- }
- let candidate = last + " " + word
- if candidate.count <= maximumCharacterPerLine {
- result[result.count - 1] = candidate
- } else if word.count <= maximumCharacterPerLine {
- result.append(word)
- } else {
- //Word is too big, we chunk it
- let chunks: [String] = stride(from: 0, to: word.count, by: maximumCharacterPerLine).map {
- let start = word.index(word.startIndex, offsetBy: $0)
- let end = word.index(start, offsetBy: maximumCharacterPerLine, limitedBy: word.endIndex) ?? word.endIndex
- return String(word[start..<end])
- }
- chunks.forEach { result.append($0) }
- }
- }
- return output
- }
- let result = wrap(text: initialStringToSend, with: characterPerLine)
- print("Result:")
- result.forEach { print($0) }
- let expected = """
- TranscribeGlass
- shows closed
- captions from any
- source in your
- field of view
- """
- print("Expected:\n\(expected)")
- }
- Outputs:
- Result:
- TranscribeGlass
- shows closed
- captions from any
- source in your
- field of view
- veryveryveryveryve
- ryverylonglongword
- Expected:
- TranscribeGlass
- shows closed
- captions from any
- source in your
- field of view
- //Side note, veryveryveryveryveryverylonglongword isn't in the expected output
Add Comment
Please, Sign In to add comment