ios - 当我在swift中将scond字符串复制到第一个字符串时,如何使用 "0"填充第一个字符串的剩余空间?

标签 ios string swift

例如,我有一个字符串: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"+ headlast 三个字符来工作:

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

关于ios - 当我在swift中将scond字符串复制到第一个字符串时,如何使用 "0"填充第一个字符串的剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765842/

相关文章:

ios - 以编程方式填充的 UITableView 无法填满屏幕

c# - 将 List<String> 中的所有字符串转换为单个逗号分隔字符串的最佳方法

swift - NSKeyedUnarchiver 检索自定义类时返回 nil

python - 在 python 中使用 str.format() 女巫类

ios - 如何纠正 iPhone X 上的 Tab Bar 高度问题

ios - 使用 Swift 在另一个 ViewController 上声明 UIViewController 变量属性

ios - Swift/Parse - 无法使用类型为 'getObjectInBackgroundWithId' 的参数列表调用 '(PFUser?, (PFObject?, NSError?) -> Void)'

iphone - iOS UITableViewCell优化

ios - 如何设置全场景导航栏背景色

java - 在Java中使用正则表达式实现简单的字符串匹配