0

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.

3 Answers 3

2

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...

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Why not using string interpolation?

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

1 Comment

Because I don't have the image name. It's responded back from server. Please check my updated question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.