0

Can I do this with less code?

urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""];
urlString = [urlString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
urlString = [urlString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
urlString = [urlString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
Mathijs
  • 1,258
  • 1
  • 10
  • 27

2 Answers2

4

If you're just wanting to trim the white space and blank lines from the beginning and end of the string, you can use

urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

This includes all of the examples you've given.

JRG-Developer
  • 12,454
  • 8
  • 55
  • 81
0

You could use a regex to remove whitespace from a string, with whitespace being anywhere in the string.

NSString *removeWhitespaceRegex = @"\\s";   

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:removeWhitespaceRegex
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSString *string = @"Remove whitespace from this string.";

NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@""];

NSLog(@"%@", modifiedString);

Just a disclaimer, the code above is written by heart with a quick lookup of some methods, some things might not work, but the idea behind it should.

The second, probably quicker way is to use an NSCharacterSet such as the JRG-Developer has mentioned, but this will remove only trailing whitespace.

Adis
  • 4,512
  • 2
  • 33
  • 40
  • Yes, `stringByTrimmingCharactersInSet` will only remove trailing or beginning characters in the set. I've updated my answer to reflect this. – JRG-Developer Dec 19 '13 at 00:14
  • Cheers, did not notice the edit :). – Adis Dec 19 '13 at 00:16
  • If you really were looking for *some pattern* of characters, regex would be the way to go. However, in this instance where it appears the OP is looking for spaces, newlines, etc, I'd expect that regex would wind up hindering performance compared to simply doing `stringByReplacingOccurrencesOfString:` as OP shows... – JRG-Developer Dec 19 '13 at 00:24