码迷,mamicode.com
首页 > 移动开发 > 详细

【iOS】去除字符串首尾空格或某字符

时间:2019-08-29 16:05:32      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:tchar   integer   set   ++   acea   nic   for   buffer   substr   

在iOS的实际开发中,常会出现需要去除空格的情况,总结有三种情况:

  • 去除字符串首尾连续字符(如空格);
  • 去除字符串首部连续字符(如空格);
  • 去除字符串尾部连续字符(如空格);

去除字符串首尾连续字符(如空格)

 NSString *a = @" a  sdf  ";
 [a stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

去除字符串首部连续字符(如空格);

 NSString *a = @" a  sdf  ";  
 NSString *leftResult = [a stringByTrimmingLeftCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
#import "NSString+util.h"

@implementation NSString (util)

- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer range:NSMakeRange(0, length)];
    
    for (NSInteger i = 0; i < length; i++) {
        if (![characterSet characterIsMember:charBuffer[i]]) {
            location = i;
            break;
        }
    }
    
    return [self substringWithRange:NSMakeRange(location, length - location)];
}

去除字符串尾部连续字符(如空格);

NSString *a = @" a  sdf  "; 
NSString *rightResult = [a stringByTrimmingRightCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer range:NSMakeRange(0, length)];
    
    NSUInteger subLength = 0;
    for (NSInteger i = length; i > 0; i--) {
        if (![characterSet characterIsMember:charBuffer[i - 1]]) {
            subLength = i;
            break;
        }
    }
    
    return [self substringWithRange:NSMakeRange(0, subLength)];
}

【iOS】去除字符串首尾空格或某字符

标签:tchar   integer   set   ++   acea   nic   for   buffer   substr   

原文地址:https://www.cnblogs.com/Free-Thinker/p/11429709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!