0

I have an url - NSString - that I obtained from an RSS feed. Unfortunately it contains a lot of white space, that I can't remove with the below code. I'm using the same code for the same work for months, but this time it does not work properly for this feed. Somehow there will be also a whitespaces, but these are not /n-s. When I click to its row on the database and trying to go through on it with the directional keys from the right to the left the cursor jumps 4-5 whitespaces everytime I tap the left arrow directional key instead of 1 whitespace per button press. Do anybody have an idea how should I handle this situation? Is it possible to remove every other typed whitespaces? Or what would be the best approach?

  NSString *stringForUrl = [feedObject[@"link"] stringByTrimmingCharactersInSet:
                                    [NSCharacterSet whitespaceCharacterSet]];

    stringForUrl = [stringForUrl stringByReplacingOccurrencesOfString:@"\n" withString:@""];           
    stringForUrl = [stringForUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    stringForUrl = [stringForUrl stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
rihekopo
  • 3,241
  • 4
  • 34
  • 63
  • 1
    `stringByTrimmingCharactersInSet` only removes characters from the start and end of the string, not in the middle. Do you have whitespace in the middle? Is the whitespace other than spaces and newlines? – rmaddy Oct 03 '15 at 21:49
  • @rmaddy it is in the end, after the exact url. – rihekopo Oct 03 '15 at 21:52
  • 1
    Try using the `whitespaceAndNewlineCharacterSet` character set. – rmaddy Oct 03 '15 at 21:53

1 Answers1

1

Try the below:

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [stringForUrl componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
finalString = [filteredArray componentsJoinedByString:@""];

Altered from here: Collapse sequences of white space into a single character and trim string

Community
  • 1
  • 1
AlexKoren
  • 1,605
  • 16
  • 28