从END修剪字符串

时间:2013-03-14 12:47:33

标签: iphone nsstring

我想从字符串的结尾串起字符串,是否有字符串的api函数,它只从字符串的END中删除空格和换行符。

我编写了手动代码,用于从字符串末尾搜索字符并删除空格和换行符,但这可能会减慢过程。

需要API函数..

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个可能对你有帮助,

-(NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
    NSUInteger location = 0;
    unichar charBuffer[[strtoremove length]];
    [strtoremove getCharacters:charBuffer];
    int i = 0;
    for ( i = [strtoremove length]; i >0; i--){
        if (![[NSCharacterSet whitespaceCharacterSet] characterIsMember:charBuffer[i - 1]]){
            break;
        }
    }
    return  [strtoremove substringWithRange:NSMakeRange(location, i  - location)];
}

 NSString *string = @"          this text has spaces before and after         ";
    NSString *trimmedString = [self removeEndSpaceFrom:string];
    NSLog(@"%@",trimmedString);