0

I was wondering how I could check whether a complete word substring exists inside a string. As a concrete example, I would like to be able to replace the word minute with foo, and the word minutes with bar.

Currently, I am using to check whether a substring exists using:

if ([text rangeOfString:word].location != NSNotFound){
    NSLog(@"Word is found");
}

However, the issue I have is that since the substring minute is always first detected, then minutes, I will always get the replacement foo, but never bar. How would I be able to detect whether the entire substrings exists in a string?

Thanks!

6
  • You would have to start with the longest string. When the substrings are in an array, you could tort it first. Commented Jun 11, 2014 at 20:12
  • You could first attempt to replace minutes, and then attempt minute. This way you'd never end with foos in any string. Commented Jun 11, 2014 at 20:12
  • Or use regular expressions to specify that these need to be whole words. Commented Jun 11, 2014 at 20:13
  • Thanks for the comments. @Julian - how would I be able to start with the longest string first? I assume there would be another method similar to rangeOfString that I could use? Commented Jun 11, 2014 at 20:14
  • It seems regex is a good way - would you be able to supply an example as an answer for how I'd go about doing "minute" vs "minutes"? Thanks Commented Jun 11, 2014 at 20:15

2 Answers 2

2

You could do this:

NSString *original = @"Here is a string in a minute with loads of minutes.";

NSString *replaceMinutes = [original stringByReplacingOccurrencesOfString:@"minutes" withString:@"bar"];

NSString *replaceMinute = [replaceMinutes stringByReplacingOccurrencesOfString:@"minute" withString:@"foo"];

NSLog(replaceMinute);
Sign up to request clarification or add additional context in comments.

1 Comment

This would make minutes become foos instead of bar
1

You can always break up your string in an array and rebuild it to another string.

NSArray* stringWords = [NSString componentsSeparatedByString:@" "]

Then you can iterate through each word and if rangeOfString returns found you replace it in the new string with whatever string you are replacing it with. This way it doesnt matter if its minute, minutes minutesss minutelkashdflkahsf, whatever.

1 Comment

Good suggestion - will give this a try and report back results.

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.