xcode 如何识别和删除换行符和空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10426194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:10:27  来源:igfitidea点击:

How to identify and remove newline and white spaces?

iosxcode

提问by amar

I am making an nsmutable array by separating a string by component it is causing a lot of new line and white spaces to be inserted in the array how to identify and remove them?

我正在通过按组件分隔字符串来制作一个 nsmutable 数组,它会导致在数组中插入大量新行和空格,如何识别和删除它们?

for (int i=0;i<contentsOfFile.count; i++) 
 {
        if(!([[contentsOfFile objectAtIndex:i]isEqual:@"\n"]||[[contentsOfFile     objectAtIndex:i]isEqual:@""]))
       [arrayToBereturned addObject:[contentsOfFile objectAtIndex:i]];
 }

this code which i am using cannot identify all new line charectors thanks

我正在使用的此代码无法识别所有新行字符,谢谢

回答by Naina Soni

To remove all extra space and \n from your string-

要从字符串中删除所有额外的空格和 \n-

NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

than prepare your contentsOfFile Array.

比准备你的 contentsOfFile 数组。

回答by Espresso

If you want an array without whitespace:

如果你想要一个没有空格的数组:

NSString *string = @"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];

回答by Yunus Nedim Mehel

stringByTrimmingCharachersInSet:only removes desired characters from the end and the beginning of the string. To remove all occurences you should use stringByReplacingOccurrencesOfString:

stringByTrimmingCharachersInSet:只从字符串的末尾和开头删除所需的字符。要删除您应该使用的所有事件stringByReplacingOccurrencesOfString:

回答by Pavel Stepanov

Swift 5 version

斯威夫特 5 版本

    let string = "Hello, stack overflow!"
    let components = string.components(separatedBy: .whitespacesAndNewlines)
    print(components) // prints ["Hello,", "stack", "overflow!"]

Also regarding string.replacingOccurrences

还有关于 string.replacingOccurrences

    let string = " Hello, stack overflow     ! "
    let noSpacingsString = string.replacingOccurrences(of: " ", with: "")
    print(components) // prints "Hello,stackoverflow!"