Character occurrences in a String Objective C

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

提交回复
热议问题