Swift - Split string over multiple lines

前端 未结 15 2054
清酒与你
清酒与你 2020-12-04 07:51

How could I split a string over multiple lines such as below?

var text:String = \"This is some text
                   over multiple lines\"
15条回答
  •  甜味超标
    2020-12-04 08:46

    Here's a code snippet to split a string by n characters separated over lines:

    //: A UIKit based Playground for presenting user interface
    
    import UIKit
    import PlaygroundSupport
    
    class MyViewController : UIViewController {
        override func loadView() {
    
            let str = String(charsPerLine: 5, "Hello World!")
            print(str) // "Hello\n Worl\nd!\n"
    
        }
    }
    
    extension String {
    
        init(charsPerLine:Int, _ str:String){
    
            self = ""
            var idx = 0
            for char in str {
                self += "\(char)"
                idx = idx + 1
                if idx == charsPerLine {
                    self += "\n"
                    idx = 0
                }
            }
    
        }
    }
    

提交回复
热议问题