Iphone 字符串目标C中的字符出现次数

Iphone 字符串目标C中的字符出现次数,iphone,objective-c,ipad,nsstring,Iphone,Objective C,Ipad,Nsstring,如何计算字符串中字符的出现次数 范例 字符串:123-456-7890 我想找到给定字符串中“-”的出现计数 replaceconcurrencesofstring:withString:options:range:方法返回进行的替换次数,因此我们可以使用它来计算字符串中有多少个-。您可以使用replaceconcurrencesofstring:withString:options:range:方法NSStringint-total=0; int total = 0; NSString *st

如何计算字符串中字符的出现次数

范例

字符串:123-456-7890

我想找到给定字符串中“-”的出现计数


replaceconcurrencesofstring:withString:options:range:
方法返回进行的替换次数,因此我们可以使用它来计算字符串中有多少个
-

您可以使用
replaceconcurrencesofstring:withString:options:range:
方法
NSString
int-total=0;
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);
NSString*str=@“123-456-7890”;
对于(int i=0;i,您可以这样做:

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

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

计数次数:2

这样就可以了

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

我是为你做的,试试这个

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);
unicharfindc;
整数计数=0;
NSString*strr=@“123-456-7890”;

对于(int i=0;i而言,如果字符串以您正在检查的字符开头或结尾,则当前选择的答案将失败

改用这个:

int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:@"-" withString:@""].length;

重复:这是否回答了您的问题?这不会导致内存泄漏,因为您没有释放副本吗?@trojanfoe您当然必须释放副本,但它超出了答案的范围。@H2CO3此代码也不可能,因为您没有指向副本的指针。它超出了范围,是的,但许多新手可能会复制它逐字编写代码,然后想知道它们为什么会泄漏内存。没错,如果你在进行手动内存管理,那么就需要
自动释放
。我已经使用ARC很长时间了,以至于我忘了不是每个人都是!这也是查找字符串中出现了多少空格的最佳代码…如果字符串以“-”开头会怎么样?@Oscar它仍然可以工作,I j我们已经测试过了。你自己试过了吗?@hfossli,你错了,它将分别返回4和2。@Cœur你完全正确!我认为你疯了。
int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:@"-" withString:@""].length;