7

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?

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

amar
  • 4,285
  • 8
  • 40
  • 52

4 Answers4

21

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

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

than prepare your contentsOfFile Array.

Naina Soni
  • 720
  • 5
  • 21
12

If you want an array without whitespace:

NSString *string = @"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];
Espresso
  • 4,722
  • 1
  • 24
  • 33
10

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

Yunus Nedim Mehel
  • 12,089
  • 4
  • 50
  • 56
0

Swift 5 version

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

Also regarding string.replacingOccurrences

    let string = " Hello, stack overflow     ! "
    let noSpacingsString = string.replacingOccurrences(of: " ", with: "")
    print(components) // prints "Hello,stackoverflow!"
Pavel Stepanov
  • 891
  • 8
  • 13