13

How can I count the occurrence of a character in a string?

Example

String: 123-456-7890

I want to find the occurrence count of "-" in given string

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 4
    Repeat: http://stackoverflow.com/questions/938095/nsstring-number-of-occurrences-of-a-character – hellslam May 14 '12 at 13:30
  • Does this answer your question? [Number of Occurrences of a Character in NSString](https://stackoverflow.com/questions/938095/number-of-occurrences-of-a-character-in-nsstring) – Jon Schneider Mar 19 '21 at 14:28

7 Answers7

38

You can simply do it like this:

NSString *string = @"123-456-7890";
int times = [[string componentsSeparatedByString:@"-"] count]-1;

NSLog(@"Counted times: %i", times);

Output:

Counted times: 2

Justin Boo
  • 10,132
  • 8
  • 50
  • 71
  • Its also best code to find how many SPACES occurred in string. . . – Mohd Sadham Jun 05 '14 at 15:16
  • 1
    What if the string starts with '-'? – Oscar Nov 13 '14 at 16:41
  • 3
    @Oscar It will still work, I just tested it. Have you tried it yourself? – CyberMew Dec 10 '14 at 04:53
  • 1
    @hfossli, you're wrong, it will return 4 and 2 respectively. – Cœur Sep 23 '15 at 01:14
  • @Cœur you are absolutely right! Crazy in my opinion. https://gist.github.com/hfossli/4c76a96b34574cb938ce – hfossli Sep 23 '15 at 06:52
  • Yup, this won't work accurately if the sub-string is at the end. Use the following replacement string, which returns the count of replacements. Easy peasy, and accurate. - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange; – Mike Critchley Jun 27 '17 at 09:57
  • Will this end up allocating a lot of new NSString instances into memory -- the split substrings that are being counted -- when the search string is large? – Jon Schneider Mar 19 '21 at 14:25
2

This will do the work,

int numberOfOccurences = [[theString componentsSeparatedByString:@"-"] count];
sElanthiraiyan
  • 6,000
  • 1
  • 31
  • 38
2

I did this for you. try this.

unichar findC;
int count = 0;
NSString *strr = @"123-456-7890";

for (int i = 0; i<strr.length; i++) {
    findC = [strr characterAtIndex:i];
    if (findC == '-'){
        count++;
    }
}

NSLog(@"%d",count);
SachinVsSachin
  • 6,401
  • 3
  • 33
  • 39
1
int num = [[[myString mutableCopy] autorelease] replaceOccurrencesOfString:@"-" withString:@"X" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];

The replaceOccurrencesOfString:withString:options:range: method returns the number of replacements that were made, so we can use that to work out how many -s are in your string.

Amy Worrall
  • 16,250
  • 3
  • 42
  • 65
  • Doesn't that cause a memory leak as you aren't releasing the copy? – trojanfoe May 14 '12 at 13:32
  • @trojanfoe You have to release the copy of course, but it's out of the scope of the answer. –  May 14 '12 at 13:34
  • 1
    @H2CO3 It's also not possible with this code as you don't have a pointer to the copy. It is out-of-scope, yes, but many newbies are likely to copy this code verbatim and then wonder why they are leaking memory. – trojanfoe May 14 '12 at 13:36
  • That's true, if you're doing manual memory management then `autorelease` is required. I've been using ARC for so long that I forget not everyone is! – Amy Worrall May 14 '12 at 13:54
1
int total = 0;
NSString *str = @"123-456-7890";
for(int i=0; i<[str length];i++)
{
    unichar c = [str characterAtIndex:i];
    if (![[NSCharacterSet alphanumericCharacterSet] characterIsMember:c])
    {
        NSLog(@"%c",c);
        total++;
    }
}
NSLog(@"%d",total);

this worked. hope it helps. happy coding :)

Anshuk Garg
  • 1,540
  • 12
  • 14
0

You can use replaceOccurrencesOfString:withString:options:range: method of NSString

Maulik
  • 19,348
  • 14
  • 82
  • 137
0

The current selected answer will fail if the string starts or ends with the character you are checking for.

Use this instead:

int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:@"-" withString:@""].length;
Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195