it's me again. I've asked a question similar to this just awhile ago but this question is a bit more complex. I was planning on using RegexKitLite to do what I needed to do but I believe this can be done with out it. I have a NSString that has some words with spaces/blanks in it and I'm wanting to get the very last space in the string that is to the left of the last word. Example String below:
NSString *string = @"Here is an example string HELLO ";
NSString *spaceReplacement = @"text that i want";
NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:@" " withString:spaceReplacement];
This solution assumes you always have a space at the end of your string... it should convert
Here is an example string HELLO
Here is an example stringtext that i wantHELLO
... since that's what I understood you wanted to do.
Here's the code:
NSString *string = @"Here is an example string HELLO "; NSRange rangeToSearch = NSMakeRange(0, [string length] - 1); // get a range without the space character NSRange rangeOfSecondToLastSpace = [string rangeOfString:@" " options:NSBackwardsSearch range:rangeToSearch]; NSString *spaceReplacement = @"text that i want"; NSString *result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace withString:spaceReplacement];
The trick is to use the
[NSString rangeOfString:options:range:] method.
Note: If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
Disclaimer: I haven't tested the code, but it should compile and work just fine.