在objective-c中,如何去掉一个string 的前后的空格字符或某个特定字符呢?
如@ “ abc 123 ”字符串前后有空格,该如何去掉?
使用nsstring 的实例方法stringByTrimmingCharactersInSet :可以解决该问题。
方法如下:
- [@" abc 123 " stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
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
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.
这是典型的其他语言中trim 方法。我要问的是,如何去掉最左边的空格?又该如何去掉最右边的空格?
在NSString 的类中没有提供实现这类需求的方法,我们只能手工去添加这些方法。
- @interface NSString (TrimmingAdditions)
- - (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet ;
- - (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet ;
- @end
- @implementation NSString (TrimmingAdditions)
- - (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
- NSUInteger location = 0;
- NSUInteger length = [self length];
- unichar charBuffer[length];
- [self getCharacters:charBuffer];
- for (location; location < length; location++) {
- if (![characterSet characterIsMember:charBuffer[location]]) {
- break;
- }
- }
- return [self substringWithRange:NSMakeRange(location, length - location)];
- }
- - (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
- NSUInteger location = 0;
- NSUInteger length = [self length];
- unichar charBuffer[length];
- [self getCharacters:charBuffer];
- for (length; length > 0; length--) {
- if (![characterSet characterIsMember:charBuffer[length - 1]]) {
- break;
- }
- }
- return [self substringWithRange:NSMakeRange(location, length - location)];
- }
- @end
使用stringByTrimmingRightCharactersInSet 方法去掉一个字符串最右边的空格。
- NSLog(@"%@",[@"abc 123 " stringByTrimmingRightCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]);
如何去掉一个字符串@ “0.012300 ”最右边的“0 “呢?这是典型的float 格式化成字符串以后的形式,显示时最好去掉最右边的“0 ”。
解决方法如下:
- [@"0.012300" stringByTrimmingRightCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"0"]];
在NSString 中trim 字符时,不理解为何不提供分别去掉左右字符的方法,如其他语言的ltrim 和rtim 。