天天看點

NSString實作trim

iOS開發過程中,有時候需要去掉給定字元串兩端的空格,避免判斷錯誤,而Java有一個trim()方法,非常好用!

那麼,NSString如何實作trim呢?上代碼:

NSString *strBeforeTrim = @"  trim test  ";
    NSLog(@"%@", strBeforeTrim);
    NSString *strAfterTrim = [strBeforeTrim stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSLog(@"%@", strAfterTrim);
           

列印結果:

2015-01-29 14:27:41.502 TestProject[278:60b]   trim test  
2015-01-29 14:27:41.505 TestProject[278:60b] trim test