Character occurrences in a String Objective C

后端 未结 7 1531
生来不讨喜
生来不讨喜 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: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

提交回复
热议问题