LondonGuy
LondonGuy

Reputation: 11108

How do I insert a string into another string after a specific letter?

I'm storing heights in my database as 62 or 511 instead of 6 ft 2 or 5 ft 11.

This is how I prepare the string that will be saved:

    let height = 6 ft 2
    let myNewString = height.stringByReplacingOccurrencesOfString(" ft ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    println(myNewString) // 62

What I'd like to do is now do the opposite thing when displaying back the data from the database.

So I'd like to take the returned "62" from the database and insert this string " ft " into it. My aim is to end up with "6 ft 2" to display on the app.

How can I do this?

I want to avoid storing two columns dedicated to height in my database. I only know how to concatenate strings but this isn't exactly concatenating a string. I am inserting it into an existing string.

I'd appreciate an efficient way to do this. Been looking around for a while now and can't seem to find my solution.

Thanks for your time.

Update:

After reading comments I'm wondering if it would be better to add a decimal point after the first char in string e.g. 4.2, 4.10, 5.4, 5.11, 6.2 etc

let height = 6 ft 2
let myNewString = height.stringByReplacingOccurrencesOfString(" ft ", withString: ".", options: NSStringCompareOptions.LiteralSearch, range: nil)
println(myNewString) // 6.2

Upvotes: 0

Views: 189

Answers (2)

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

Swift’s String conforms to RangeReplaceableCollectionType, which has a splice method – splice allows you to insert a collection into another collection. Since strings are collections, that means you can write:

var height = "62"
if !height.isEmpty {
    height.splice(" ft ", atIndex: height.startIndex.successor())
} // height is now "6 ft 2"

Alternatively if you know you only want the first character before the “ft” you can do:

let height = "62"
if let feet = first(height) {
    let inches = dropFirst(height)
    let heightWithFt = "\(feet) ft \(inches)"
}

Upvotes: 2

rob mayoff
rob mayoff

Reputation: 386018

It would probably be a better idea to store the height purely in inches (e.g. store 74 for 6'2").

Anyway:

    let input = "62"
    let feet = (input as NSString).substringToIndex(1)
    let inches = (input as NSString).substringFromIndex(1)
    let output = "\(feet) ft \(inches)"

If you don't like the use of NSString, you can avoid it this way:

    let input = "62";
    let feet = input.substringToIndex(input.startIndex.successor())
    let inches = input.substringFromIndex(input.startIndex.successor())
    let output = "\(feet) ft \(inches)"

Upvotes: 2

Related Questions