1

For example, I have a string: let one = "1" , and I have another string:

let two = "123"

Now I have a function:

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


}

For example, if I call this function like this:

myfunc(one,"hello")

it will return 001hello, if I call it like this:

myfunc(two,"hello")

it will return 123hello if I call it like this:

myfunc("56","wolrd")

it will return

056world

Here is my 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)))
}
}

what should I do ? How to insert 0 at the beginning of the string:return_value?

beasone
  • 1,073
  • 1
  • 14
  • 32

2 Answers2

3

There are many possible approaches, this is just one:

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

It works by taking the last three characters of "000" + head:

myfunc("1", "hello")   // "001hello"
myfunc("123", "hello") // "123hello"
myfunc("56", "world")  // "056world"
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

First off, you don't need the String extension. This method will append 0's to the beginning of head until it is 3 characters, then concatenate the two strings.

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
}
keithbhunter
  • 12,258
  • 4
  • 33
  • 58