I want to remove only first space in below string.
NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after GET_Mi. I am unable to remove the space after IF_Distance.
I want to remove only first space in below string.
NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString:
to locate the first space, then use stringByReplacingCharactersInRange:withString:
to replace it with the empty string.
Remove space by using below code.
NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:@"IF_Distance " withString:@"IF_Distance"];
Try This:
NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:@"%@ ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output: str = @"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString:
and then remove by using stringByReplacingCharactersInRange:withString:
method.
Like,
NSString *str = @"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = @" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:@""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:@" "]];
}