创建一个包含n个空格或其他重复字符的字符串 [英] Create a string with n blank spaces or other repeated character
问题描述
我想使用Swift创建一个带有 n 空格的字符串,但不使用 for
循环或手动像这样:
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 = " "
推荐答案
字符串
已经有 重复:count:
初始化程序就像数组
(以及采用 <$ c的其他系列$ c> RangeReplaceableIndexable 协议):
String
already has a repeating:count:
initializer just like Array
(and other collections that adopt the RangeReplaceableIndexable
protocol):
init(repeating repeatedValue: String, count: Int)
所以你可以打电话:
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) // -> "-=-=-=-=-="
编辑:更改为Swift 3语法并删除了对Swift 1类型模糊问题的讨论。如果您需要使用旧版本,请参阅编辑历史记录。
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.
这篇关于创建一个包含n个空格或其他重复字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!