Character occurrences in a String Objective C

后端 未结 7 1523
生来不讨喜
生来不讨喜 2021-02-19 19:01

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 \"-\

相关标签:
7条回答
  • 2021-02-19 19:40

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

    0 讨论(0)
  • 2021-02-19 19:43

    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;
    
    0 讨论(0)
  • 2021-02-19 19:44
    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.

    0 讨论(0)
  • 2021-02-19 19:46

    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

    0 讨论(0)
  • 2021-02-19 19:57

    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);
    
    0 讨论(0)
  • 2021-02-19 19:58

    This will do the work,

    int numberOfOccurences = [[theString componentsSeparatedByString:@"-"] count];
    
    0 讨论(0)
提交回复
热议问题