简体   繁体   中英

iOS - How to insert a character in a specific place inside a string?

I have an url that looks something like this: " http://www.thisIsMyLink.com/afAFFgsfFGsgsdfgds.jpg "

The thing is that I need to add "_s" to the end of the url just before the ".jpg". So what I need would be this: http://www.thisIsMyLink.com/afAFFgsfFGsgsdfgds_s.jpg

I found one way to put specific characters inside a string like this:

NSMutableString *mu = [NSMutableString stringWithString:myUrl];
[mu insertString:@"_s" atIndex:5];

which will add the "_s" in the 5th character inside the string. The problem is that I don't know every time the length of the link because of the identifier which comes before the ".jpg", so what I need is to always place the "_s" 4 characters before the end so that it appears just before the ".jpg".

How can I do that?

Thanks for reading my post :)

What about this:

NSMutableString *mu = [NSMutableString stringWithString:myUrl];
[mu insertString:@"_s" atIndex:[mu length] - 4];

You should ensure, though, that [mu length] is always >= 4.

There might be clever ways to do that, but you do not specify how you get the original url from. One option would be using stringWithFormat to build your string modularily.

Here is another one that would work for any extension (.jpeg for instance):

NSString *test = @"www.thisIsMyLink.com/afAFFgsfFGsgsdfgds.jpg";
NSString *ext = [test pathExtension]; // This is .jpg in this case
NSString *out = [[[test stringByDeletingPathExtension] stringByAppendingString:@"_s"] stringByAppendingPathExtension:ext];

So the logic here is:

  1. Get your path's extension
  2. Delete the extension
  3. Add your string
  4. Add the extension

That way you avoid relying on any assumptions (such as that you always have a 3 letter extension). Worst case scenario, to have no extension at all and end with a path with your string appended in the end of it. I hope that this helped.

Try this one:

[mu insertString:@"_s" atIndex:[mu length] - 3];

Untested.

Case insensitive replacing of the last instance of ".jpg" with "_s.jpg". This avoids url mangling in the case where you have ".jpg" somewhere else in the url for some reason.

NSString *extension = @".jpg";
NSMutableString *mu = [NSMutableString stringWithString:myUrl];
[mu insertString@"_s" atIndex[[[url lowercaseString] rangeOfString:extension options:NSBackwardsSearch].location];

NSString has a method called length which returns the length of the string. Subtract the length of the extension (4), and you have your start index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM