user1302553
user1302553

Reputation:

Character occurrences in a String Objective C

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

Upvotes: 13

Views: 16669

Answers (7)

Albert Renshaw
Albert Renshaw

Reputation: 17882

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;

Upvotes: 0

Amy Worrall
Amy Worrall

Reputation: 16337

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.

Upvotes: 1

SachinVsSachin
SachinVsSachin

Reputation: 6427

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);

Upvotes: 2

sElanthiraiyan
sElanthiraiyan

Reputation: 6268

This will do the work,

int numberOfOccurences = [[theString componentsSeparatedByString:@"-"] count];

Upvotes: 2

Justin Boo
Justin Boo

Reputation: 10198

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

Upvotes: 38

Anshuk Garg
Anshuk Garg

Reputation: 1540

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 :)

Upvotes: 1

Maulik
Maulik

Reputation: 19418

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

Upvotes: 0

Related Questions