Pham Hoan
Pham Hoan

Reputation: 2127

insert a String inside another String

How can I make this:

var originalString = "http://name.domain.com/image.jpg"

becomes this:

originalString = "http://name.domain.com/image_new.jpg"

I could not find any document about the new Range<String.Index> in Swift.
This is not a problem in Obj-C, but without any reference about Range, it suddenly becomes so confusing.

Thanks.


Edit: Well, thanks for these solutions. However, let me give you more details about this question.
After uploading an image to server, it responds back with a String link, like above, and the image name is a random string.
The server also generates different versions of uploaded image (like Flickr). In order to get these images, I have to append a suffix into image name, it looks like this:

originalString = "http://image.domain.com/randomName_large.jpg" or "http://image.domain.com/randomName_medium.jpg"

So that's why I need to insert a String into another String. My solution is find the first . by scan the link backwardly and append a suffix before it, but the new Range<String.Index> makes it confusing.

Upvotes: 0

Views: 124

Answers (3)

Thomas M&#252;ller
Thomas M&#252;ller

Reputation: 15635

There are some nice and useful methods on NSString that you should be able to use:

let originalString: NSString = "http://name.domain.com/image.jpg"

let extension = originalString.pathExtension // "jpg"
let withoutExt = originalString.stringByDeletingPathExtension() // "http://name.domain.com/image"
let imageName = withoutExt.lastPathComponent // "image"
let withoutFilename = withoutExt.stringByDeletingLastPathComponent() // "http://name.domain.com/"

let newString = withoutFilename
  .stringByAppendingPathComponent("\(imageName)_new")
  .stringByAppendingPathExtension(extension)

I only typed this into the browser (it's untested) but it should give you an idea...

Upvotes: 2

NSMutableString
NSMutableString

Reputation: 10743

Why not using string interpolation?

var imageName = "image_new"
originalString = "http://images.domain.com/\(imageName).jpg"

Upvotes: 0

Martin R
Martin R

Reputation: 540075

This can be done with String manipulation functions. But what if the string is

var originalString = "http://images.domain.com/image.jpg"

? You probably do not want to replace the first or all occurrences of the string "image" here.

A better tool for this purpose might be NSURLComponents, which lets you modify all components of a URL separately:

var originalString = "http://name.domain.com/image.jpg"
let urlComps = NSURLComponents(string: originalString)!
urlComps.path = "/image_new.jpg"
originalString = urlComps.URL!.absoluteString!

println(originalString) // http://name.domain.com/image_new.jpg

Upvotes: 0

Related Questions