在Swift中重复String

时间:2016-02-19 17:07:10

标签: swift function swift2 repeat

我的任务是创建一个函数,该函数接受一个字符串和int的两个参数,它将返回一个字符串,该字符串重复字符串参数int的次数。这是我提出的但是出错了。顺便说一句,这是我在CodeCardio上工作的,所以我还没有能够在Xcode中测试它(我的工作很糟糕并使用Windows)

  func repeater(aString: String, withNumber: Int) -> String {
      let repeatedString = String(count: withNumber, repeatedValue: aString)
      return repeatedString
  }

8 个答案:

答案 0 :(得分:5)

String(count: withNumber, repeatedValue: aString)

用于实例化具有重复字符的字符串:Does Swift init(count:, repeatedValue:) work?

取而代之的是

func repeater(string: String, withNumber number: Int) -> String {
    var repeatedString = String()
    for i in 0..<number {
        repeatedString += string
    }
    return repeatedString
}

答案 1 :(得分:2)

repeatedValue的参数类型String(count: repeatedValue: aCharacter)Character而不是String

您可以使用Array(count: withNumber, repeatedValue: aString)并加入项目

func repeater(aString: String, withNumber: UInt) -> String {
  let repeatedArray = Array(count: Int(withNumber), repeatedValue: aString)
  return repeatedArray.joinWithSeparator("")
}

答案 2 :(得分:1)

我稍微修改了Tanguy的答案。现在,如果第二个参数小于0,则函数不会崩溃,但返回空字符串

func repeate(string: String,  times: Int) -> String {
    var repeatedString = ""
    var n = times
    while n > 0 {
        repeatedString += string
        n -= 1
    }
    return repeatedString
}

同样的问题有Vadian的答案,检查参数并尽早返回“”可能是最好的解决方案。我个人更喜欢Vadian的方法。

答案 3 :(得分:1)

你可以这样做:

func repeater(aString string: String, withNumber number: Int) -> String {
    return [String](count: number, repeatedValue: string).reduce("", combine: +)
}

答案 4 :(得分:1)

迅速5:

extension String {
    func repeater(by count: Int) -> String {
        return String(repeating: self, count: count)
    }
}

调用:“ testString” .repeater(通过:计数器)

答案 5 :(得分:0)

func repeatAString(anyString: String, numberOfTimes: Int) ->String
{
    var returnString: String = String()
    for _ in 1...numberOfTimes 
    {
        returnString = returnString.stringByAppendingString(anyString)
    }
    return returnString
}

您好我使用了stringByappendingString来解决这个问题。我看到你有很多答案,但是没有人建议,所以我想把它放在那里。干杯!

答案 6 :(得分:0)

从Swift 3开始,init(repeating:count:)也可以接受String参数。

var repeatingString = String(repeating: "ab", count: 7)
print(repeatingString) // ababababababab

尝试一下:

func repeater(aString: String, withNumber: Int) -> String {
    let repeatedString = String(repeating: aString, count: withNumber)
    return repeatedString
}

答案 7 :(得分:-1)

func repeater(aString: String, withNumber: Int) -> String 
{
var repeatedString=""
for var index = 0; index < withNumber; ++index 
   {
     repeatedString=repeatedString+aString
   }
return repeatedString
}

for Function Call我使用:  print(repeater(&#34; String&#34;,withNumber:5))