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!

有帮助吗?

解决方案

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.

其他提示

You can search a NSString for any spaces like this:

NSString* string;
string = [[NSString alloc] initWithFormat:@"Hello World"];
if ([string rangeOfString:@" "].location == NSNotFound) {
     NSLog(@"Has space");
}
else {
     NSLog(@"Doesn't have space");
}

The good thing about this is that once you find that a NSStrin has a space, you can locate it by calling [string rangeOfString@" "]; which will return a NSRange that is at the location of the space. You can even remove the space by calling string = [string stringByReplacingCharactersInRange:[string rangeOfString:@" " withString:@""];

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top