Create a string with n blank spaces or other repeated character

后端 未结 4 1935
一生所求
一生所求 2020-12-15 05:55

I want to make a string with n blank spaces using Swift, but without using a for loop or manually like this:

// string with 5-blank spa         


        
相关标签:
4条回答
  • 2020-12-15 06:19

    2020 | SWIFT 3.0 - 5.1:

    I like syntax of c# for doing this action. So I wrote an extension:

    static func * (str: String, repeatTimes: Int) -> String {
        return String(repeating: str, count: repeatTimes)
    }
    

    and now you're able to do this by the following way:

    let tenSpaces = " " * 10
    let ab15Times = "ab" * 15
    
    0 讨论(0)
  • 2020-12-15 06:21

    I think we can play with stringbyPaddingToLength

    something like this should work:

    var str = " ";
    var str2 = str.stringByPaddingToLength(20, withString: " ", startingAtIndex: 0);
    
    0 讨论(0)
  • 2020-12-15 06:30

    String already has a repeating:count: initializer just like Array (and other collections that adopt the RangeReplaceableIndexable protocol):

    init(repeating repeatedValue: String, count: Int)
    

    So you can just call:

    let spaces = String(repeating: " ", count: 5) // -> "     "
    

    Notice that the repeated parameter is a string, not just a character, so you can repeat entire sequences if you want:

    let wave = String(repeating: "-=", count: 5) // -> "-=-=-=-=-="
    

    Edit: Changed to Swift 3 syntax and removed discussion of Swift 1 type ambiguity issues. See the edit history if you need to work with old versions.

    0 讨论(0)
  • 2020-12-15 06:42

    In Swift 3:

    var s = String(repeating: " ", count: 5)
    

    https://developer.apple.com/reference/swift/string/2427723-init

    0 讨论(0)
提交回复
热议问题