views:

350

answers:

1

I'm creating some code that will find a space between characters, and use the characters before the space and the ones after it. These characters are stored in a NSString. Here is what I have so far, however, it's not seeing the empty character.

    NSString *tempTitle = self.title;
unsigned int indexOfSpace; // Holds the index of the character with the space
unsigned int titleLength = (unsigned int)self.title.length; // Holds the length of the title
for (unsigned int count = 0; count < titleLength; count++)
{
    if ([tempTitle characterAtIndex:count] == "") // If the character at the index is blank, store this and stop
    {
        indexOfSpace == count;
    }
    else // Else, we keep on rollin'
    {
        NSLog(@"We're on character: %c", [tempTitle characterAtIndex:count]);
    }
}

I've tried nil , empty string ("") and " " but no avail. Any ideas?

+3  A: 

Your space character should be in single quotes, not double quotes. Single quotes get you the char type in C. (Double quotes create a string literal, which essentially functions as a char * and will never pass your comparison.)

-[NSString characterAtIndex:] returns a type unichar, which is an unsigned short, so you should be able to compare this directly to a space character ' ', if that's what you want to do.

Note that nil and empty string, are not useful here-- neither are actually characters, and in any case your string will never "contain" these.

You should see also the NSString methods for finding characters in strings directly, e.g. -[NSString rangeOfString:] and its cousins. That prevents you from writing the loop yourself, although those are unfortunately a little syntactically verbose.

quixoto
Ah this worked! Thanks! I will look into the rangeOfString method, if it's as verbose as you're saying, I may just keep my method of things, as it's working.
Yakattak
If you're doing this more than once and want a simpler interface to it, you could consider adding a "category" (search for this) to NSString that provides the functionality in one transparent place.
quixoto