[英]How to identify and remove newline and white spaces?
我正在通過按組件分隔字符串來創建一個 nsmutable 數組,它會導致在數組中插入大量新行和空格,如何識別和刪除它們?
for (int i=0;i<contentsOfFile.count; i++)
{
if(!([[contentsOfFile objectAtIndex:i]isEqual:@"\n"]||[[contentsOfFile objectAtIndex:i]isEqual:@""]))
[arrayToBereturned addObject:[contentsOfFile objectAtIndex:i]];
}
我正在使用的此代碼無法識別所有新行字符,謝謝
要從字符串中刪除所有額外的空格和 \\n-
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
比准備你的 contentsOfFile 數組。
如果你想要一個沒有空格的數組:
NSString *string = @"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];
stringByTrimmingCharachersInSet:
只從字符串的末尾和開頭刪除所需的字符。 要刪除所有出現,您應該使用stringByReplacingOccurrencesOfString:
斯威夫特 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!"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.