[NSString stringByTrimmingCharactersInSet]
Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Parameters
- set
- A character set containing the characters to remove from the receiver. set must not be
nil
.
Return Value of [NSString stringByTrimmingCharactersInSet]
A new string made by removing from both ends of the receiver characters contained in set. If the receiver is composed entirely of characters from set, the empty string is returned.
Discussion of [NSString stringByTrimmingCharactersInSet]
Use
whitespaceCharacterSet
or whitespaceAndNewlineCharacterSet
to remove whitespace around strings.
Example of [NSString stringByTrimmingCharactersInSet]
NSString *testString = @" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Example of [NSString stringByTrimmingCharactersInSet]
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);
Example of [NSString stringByTrimmingCharactersInSet]
NSString * str_aLine = @" this is text \t , and\tTab between , so on ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];