我通过按组件分隔字符串来创建一个nsmutable数组,这会导致在数组中插入大量新的行和空格以便如何识别和删除它们?
for (int i=0;i<contentsOfFile.count; i++)
{
if(!([[contentsOfFile objectAtIndex:i]isEqual:@"\n"]||[[contentsOfFile objectAtIndex:i]isEqual:@""]))
[arrayToBereturned addObject:[contentsOfFile objectAtIndex:i]];
}
我正在使用的这段代码无法识别所有新的线路查找器 感谢
答案 0 :(得分:21)
删除字符串中的所有额外空格和\ n -
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
而不是准备你的contentsOfFile数组。
答案 1 :(得分:12)
如果你想要一个没有空格的数组:
NSString *string = @"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];
答案 2 :(得分:9)
stringByTrimmingCharachersInSet:
仅从字符串的结尾和开头删除所需的字符。要删除所有出现,请使用stringByReplacingOccurrencesOfString:
答案 3 :(得分:0)
Swift 5版本
let string = "Hello, stack overflow!"
let components = string.components(separatedBy: .whitespacesAndNewlines)
print(components) // prints ["Hello,", "stack", "overflow!"]
还涉及string.replacingOccurrences
let string = " Hello, stack overflow ! "
let noSpacingsString = string.replacingOccurrences(of: " ", with: "")
print(components) // prints "Hello,stackoverflow!"