例如,我有一个字符串: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
这是我的 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
?
最佳答案
有很多可能的方法,这只是一种:
func myfunc(head:String, _ body:String) -> String
{
return String(("000" + head).characters.suffix(3)) + body
}
它通过取"000"+ head
的last 三个字符来工作:
myfunc("1", "hello") // "001hello"
myfunc("123", "hello") // "123hello"
myfunc("56", "world") // "056world"
关于ios - 当我在swift中将scond字符串复制到第一个字符串时,如何使用 "0"填充第一个字符串的剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765842/