Reputation: 4170
My string is @"Hello, I am working as an ios developer"
Now I want to remove all characters after word "ios"
Ultimately I want to remove all characters after last white space character.
How can I achieve this?
Upvotes: 3
Views: 2203
Reputation: 5076
I agree with @Bhavin, but I think, better is using of [NSCharacterSet whitespaceCharacterSet] to determine whitespace characters.
NSString* str= @"Hello, I am working as an ios developer";
// Search from back to get the last space character
NSRange range= [str rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet] options:NSBackwardsSearch];
// Take the first substring: from 0 to the space character
NSString* finalStr = [str substringToIndex: range.location]; // @"Hello, I am working as an ios"
Upvotes: 4
Reputation: 2805
you can also Achieve this using REGEX
NSString* str= @"Hello, I am working as an ios developer";
NSString *regEx = [NSString stringWithFormat:@"ios"];///Make a regex
NSRange range = [str rangeOfString:regEx options:NSRegularExpressionSearch];
if (range.location != NSNotFound)
{
NSString *subStr=[str substringToIndex:(range.location+range.length)];
}
this will search for first "ios" keyword and will discard after words
Hope it will help.
Upvotes: 1
Reputation: 27225
Sample Code :
NSString* str= @"Hello, I am working as an ios developer";
// Search from back to get the last space character
NSRange range= [str rangeOfString: @" " options: NSBackwardsSearch];
// Take the first substring: from 0 to the space character
NSString* finalStr = [str substringToIndex: range.location]; // @"Hello, I am working as an ios"
Upvotes: 9