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

Posted free-thinker

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS去除字符串首尾空格或某字符相关的知识,希望对你有一定的参考价值。

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去除字符串首尾空格或某字符的主要内容,如果未能解决你的问题,请参考以下文章

去除字符串首尾的空格

java去除字符串空格

字符串首尾空格去除问题

Python实践-4切片操作去除字符串首尾的空格

Java中去除字符串中空格的方法

如何用 js 去掉字符串首尾空格