美文网首页
【iOS】去除字符串首尾空格或某字符

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

作者: lever_xu | 来源:发表于2017-07-25 17:41 被阅读0次

在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】去除字符串首尾空格或某字符

    在iOS的实际开发中,常会出现需要去除空格的情况,总结有三种情况: 去除字符串首尾连续字符(如空格); 去除字符串...

  • php笔记(进阶2)

    去除字符串首尾的空格 trim( " 空格 " )去除一个字符串两端空格 rtrim(" 空格 ")去除一个字符串...

  • 4.php字符串操作

    去除首尾空格和特殊字符 PHP中提供了三个去除首尾空格和特殊字符的方法: 1)trim() 函数用来去除字符串左右...

  • js/java去除首尾空格(全角/半角)字符

    java中使用trim()去除字符串首尾空格字符,发现使用该方法无法去除字符串空格,将空格转换成对应的ascii码...

  • 常用字符串函数:

    //去除字符串首尾空格和特殊字符 trim() //截取字符串 substr() 、mb_substr() //查...

  • PHP全栈学习笔记3

    trim()函数,用于去除字符串首尾空格和特殊字符返回的是去掉的空格和特殊字符后的字符串 ltrim()函数,用于...

  • PHP全栈学习笔记3

    trim()函数,用于去除字符串首尾空格和特殊字符返回的是去掉的空格和特殊字符后的字符串 ltrim()函数,用于...

  • php底层rtrim的一个“bug”

    php底层rtrim的一个“bug” 背景 trim系列函数是用于去除字符串中首尾的空格或其他字符。ltrim函数...

  • PHP基础 —— 字符串处理

    字符串处理 字符串处理 去除字符串首尾字符 trim() 去除字符串首尾两边的空白字符(或者其他字符) " ",空...

  • PHP系统函数----常用字符串函数

    去空格或者其他字符串 trim() :去除首尾空白字符 空白字符包括:\t,\n,"",\0,\xoB rtrim...

网友评论

      本文标题:【iOS】去除字符串首尾空格或某字符

      本文链接:https://www.haomeiwen.com/subject/aatgkxtx.html