【问题标题】:how to use "0" to fill the rest space of the first string when I copy scond string into the first string in swift?当我将第二个字符串快速复制到第一个字符串中时,如何使用“0”填充第一个字符串的剩余空间?
【发布时间】:2016-02-19 08:23:22
【问题描述】:

例如,我有一个字符串:let one = "1",我还有另一个字符串:

let two = "123"

现在我有一个函数:

func myfunc(head:String,body:String) -> String
{
   //following are pseudo code
   var return_string: String
   return_string[0...2] = head
  // the passing parameter: head's length will be equal or less than 3 charactors
   //if the string: head's length is less than 3, the other characters will be filled via "0"
     return_string[3...end] = body//the rest of return_string will be the second passing parameter: body


}

例如,如果我这样调用这个函数:

myfunc(one,"hello")

如果我这样称呼它,它将返回001hello

myfunc(two,"hello")

它将返回123hello 如果我这样称呼它:

myfunc("56","wolrd")

它会返回

056world

这是我的extension to String

extension String {
var length: Int {
    return self.characters.count
}
subscript (i:Int) -> Character{
    return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
    return String(self[i] as Character)
}

subscript (r: Range<Int>) -> String {
    return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
}
}

我该怎么办?如何在字符串开头插入0:return_value

【问题讨论】:

标签: ios string swift


【解决方案1】:

首先,您不需要String 扩展名。该方法会在head的开头追加0直到3个字符,然后将两个字符串连接起来。

func myFunc(var head: String, body: String) -> String {
    while head.characters.count < 3 {
        head.insert("0", atIndex: head.startIndex)
    }
    head = head.substringToIndex(head.startIndex.advancedBy(3))
    return head + body
}

【讨论】:

    【解决方案2】:

    有很多可能的方法,这只是一种:

    func myfunc(head:String, _ body:String) -> String
    {
        return String(("000" + head).characters.suffix(3)) + body
    }
    

    它通过取"000" + head最后一个三个字符来工作:

    myfunc("1", "hello")   // "001hello"
    myfunc("123", "hello") // "123hello"
    myfunc("56", "world")  // "056world"
    

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 2020-02-14
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 2019-01-21
      相关资源
      最近更新 更多