Replace whitespace-groups with s single white space

I just checked NSString and NSCharacterSet and was wondering if anybody has yet put together a little code snipped to replace all whitespace-groups (either including or excluding linefeed/car.return) of a NSString with a single whitespace? Is there something pre-baked?



Thanks for listening!

The simplest way is probably to use [NSString componentsSeparatedByCharactersInSet:], then create a new array by filtering out the empty strings, then using [NSArray componentsJoinedByString:] to reconstitute the string.


Something like this:


NSArray* array = [string componentsSeparatedByCharactersInSet: [NSCharacterSet whiteSpaceCharacerSet]];
NSIndexSet* indexes = [array indexesOfObjectsPassingTest: ^BOOL (NSString* string, NSUInteger index, BOOL* stop) { return string.length != 0; }]
NSString* string = [[array objectsAtIndexes: indexes] componentsJoinedByString: @" "];


However, this is not a great solution if the string is very long and has lots of whitespace. In that case, you might look into using NSScanner instead.

@Quincey: Thanks - that's what I thought...


I was just hoping there is something pre-baked because even Numbers on my iPad does have a function for this :-)

Bye the bye - do you happen to know where I can find these babies:


doubleClickAtIndex:

nextWordFromIndex:forward:

lineBreakBeforeIndex:withinRange:

Word and Line Calculations in Attributed Strings


The Application Kit’s extensions to

NSAttributedString
support the typical behavior of text editors in selecting a word on a double-click with the
doubleClickAtIndex:
method, and finds word breaks with
nextWordFromIndex:forward:
. It also calculates line breaks with the
lineBreakBeforeIndex:withinRange:
method.



--

Using NSRegularExpression is another way.

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[[:whitespace:]]" options:0 error:nil];
        NSString *inputString = @"abc\ndef\rghi\tjkl";
        NSString *outputString = [regex stringByReplacingMatchesInString:inputString options:0 range:NSMakeRange(0, inputString.length) withTemplate:@" "];
        NSLog(@"output=%@", outputString); //->output=abc def ghi jkl

These are part of AppKit, so you'll find them in a category in the

NSAttributedStringKitAdditions
category in
<AppKit/NSAttributedString.h>
.

AFAICT they are not available on iOS.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Replace whitespace-groups with s single white space
 
 
Q