Reputation: 1153
I am trying to see if there is a short way of doing the following:
let s say I have the following NSString:
@"123456 copy cat";
I need to remove everything before "copy" and the length of the text before it is variable (depends on the user input)
I know that I can probably do an endless for loop to check the substring but I hope that there is a faster way
Upvotes: 0
Views: 5221
Reputation: 6036
NSString *string = @"123456 copy cat";
NSRange range = [string rangeOfString:@"copy"];
NSString *newString = [string substringFromIndex:range.location];
That's the simple answer. The problem is that your user may enter the word 'copy', and then what? Even if you get the range this way:
NSRange range = [string rangeOfString:@"copy cat"];
there's still a chance your user may enter that phrase as well. By the time you put in additional checks, it's no longer a "short way."
EDIT
Don't overlook Chuck's excellent observation in the comments for using:
-[NSString rangeOfString:options:]
Upvotes: 12
Reputation: 6131
To remove part of a string you will either have to create a new string containing the part that you want to keep, or create a mutable copy of your string and modify that.
To create a new string containing the part starting with "copy":
NSString *input;
NSString *output;
NSRange copyRange;
input = @"123456 copy cat";
copyRange = [input rangeOfString:@"copy"];
output = [input substringFromIndex:copyRange.location];
To create a mutable string and remove the part up to "copy":
NSString *input;
NSMutableString *output;
NSRange copyRange;
input = @"123456 copy cat";
output = [input mutableCopy];
copyRange = [output rangeOfString:@"copy"];
[output replaceCharactersInRange:NSMakeRange(0, copyRange.location) withString:@""];
[output autorelease]; // depending on what you want to do
Please also see the comments in the other answer about using rangeOfString:withOptions: with NSBackwardsSearch in case the user input also contains the word "input".
Upvotes: 2