Search code examples
iosunicodensstringnscharacterset

Detect the presence of nonbreaking space in NSString?


I'm trying to create an NSCharacterSet that I can use to test whether a character is a whitespace or not. This character set:

[NSCharacterSet whitespaceAndNewlineCharacterSet]

does not include non-breaking spaces, so I'm attempting to build my own whitespace character set.

myWhiteSpaceCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"  \n\r\t"];

The first character in my character set is just a space created with the space bar. The second character will appear to be a space on your browser, however in XCode it appears as a dot, which represents a non-breaking space. I created it by holding down the option key on my Mac and then hitting the spacebar.

To test for membership I tried this:

NSString* nonBreakingSpace = @" ";
char nonBreakingSpaceChar = [nonBreakingSpace characterAtIndex:0];
if ([myWhiteSpaceCharacterSet characterIsMember:nonBreakingSpaceChar]) {
  NSLog(@"YES");
} else {
  NSLog(@"NO");
}

The character in the NSString nonBreakingSpace was created with option-spacebar. Yet this code prints NO.

Any idea what I might be doing wrong? Or does anyone know of an existing character set that includes all possible kinds of whitespace? I'm sure I'm missing some...

Thanks!


Solution

  • Use unichar instead of char. That's the return type of characterAtIndex: and the non-breaking space character doesn't fit into one byte, so the value is truncated when you implicitly cast it to a char.