Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a backwards search to find the 2nd space/blank and replace it with another string?

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 ";

As you can see in the string above there is a space/blank at the very end of the string. I'm wanting to be able to get the space/blank to the left of HELLO and replace it with my own text/string. I'm working on using the NSString's NSBackwardsSearch but it's not working.

NSString *spaceReplacement = @"text that i want";
    NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:@" " withString:spaceReplacement];
    NSLog(@"%@", replaced);

Any help would help, I'm just tired of trying to fix this thing, it's driving me bonkers. I thought I could do this with RegexKitLite but the learning curve for that is too steep for me considering my timeframe I'm working with. I'm glad Jacob R. referred me to use NSString's methods :-)

like image 337
0SX Avatar asked Dec 02 '22 04:12

0SX


2 Answers

This solution assumes you always have a space at the end of your string... it should convert

Here is an example string HELLO

... to:

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.

like image 140
Senseful Avatar answered Dec 04 '22 06:12

Senseful


Something like this should work:

NSString *string = @"Here is an example string HELLO ";

if ([string hasSuffix:@" "]) {
    NSString *spaceReplacement = @"text that i want";
    NSString *replacedString = [[string substringToIndex:
            [string length]] stringByAppendingString:spaceReplacement];
    NSLog(@"replacedString == %@", replacedString);
}
like image 30
NSGod Avatar answered Dec 04 '22 06:12

NSGod