Counting character occurence in NSString

Discussion in 'Mac Programming' started by StijnSpijker, Jan 27, 2009.

  1. macrumors newbie

    Joined:
    Jan 27, 2009
    Location:
    The Netherlands
    #1
    I'm just working on my very first Cocoa project. I already know a number of other languages such as C / C++ / C# / Java etc..

    I'm actually trying to accomplish a simple task: Finding the number of occurences of the character '-' in an NSString. Now, I could write a 6 line while loop to do this for me, but to be honest, I expected the Cocoa framework to have a method for me?

    I could only think of one alternative way: rangeOfCharacterFromSet. And then looping that until the end of the string (but this would be inferior to looping once, of course..).

    Have I missed a vital search keyword on google (I could not find a -single- article about finding the number of occurences in an NSString)? I did find a some articles about having a CountedSet, but you would have to have an array? (Do I have to go back to char arrays??).

    I would appreciate some hints as a first time user. Thanks!
     
  2. macrumors 68020

    LostSoul80

    Joined:
    Jan 25, 2009
    #2
    Maybe this can be a workaround (put this in your NSString subclass)

    Code:
    - (NSInteger)occurrencesOfCharacter:(char *)c
    {
        if (c == NULL) return -1;
    
        NSString * s = [NSString stringWithCString: c encoding: NSUTF8StringEncoding]; // can be every encoding you want...
        if ([self isEqualToString: s]) return 1; // just to avoid useless work
        NSUInteger  cnt = [[self componentsSeparatedByString: s] count];
        return cnt - 1;
    }
    
    Hope that helps.
     
  3. thread starter macrumors newbie

    Joined:
    Jan 27, 2009
    Location:
    The Netherlands
    #3
    Thanks!
    But I think that writing the while loop myself requires less lines of code, and has WAY better readability :p..

    I conclude from this post that there is no such method in the framework, and will write my own helper class..
     
  4. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    Shorter version :)
    Code:
    - (int)occurrencesOfString:(NSString *)str
    {
        return [[self componentsSeparatedByString:str] count]-1;
    }
    I'd avoid using chars directly if working with NSStrings.
     

Share This Page