NSString *cleanString = [dirtyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
还有就是去除多于的空格,如下:
NSString *theString = @" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];
本文介绍如何使用Objective-C中的NSString方法来清除字符串中的多余空格及换行符。通过具体代码示例展示了如何创建一个干净的字符串,包括去除首尾空白字符以及过滤掉空字符串组件。
1万+

被折叠的 条评论
为什么被折叠?



