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 space
var s = " "
StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; ++i) { sb. append(c); } String result = sb. toString();
We can easily use the Python join() function to create a string of n characters.
String. format("%5c", ' '); Makes a string with 5 spaces.
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').
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.
In Swift 3:
var s = String(repeating: " ", count: 5)
https://developer.apple.com/reference/swift/string/2427723-init
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With