【发布时间】:2012-05-14 13:25:21
【问题描述】:
如何计算字符串中某个字符的出现次数?
例子
字符串:123-456-7890
我想在给定的字符串中找到“-”的出现次数
【问题讨论】:
标签: iphone objective-c ipad nsstring
如何计算字符串中某个字符的出现次数?
例子
字符串:123-456-7890
我想在给定的字符串中找到“-”的出现次数
【问题讨论】:
标签: iphone objective-c ipad nsstring
你可以这样做:
NSString *string = @"123-456-7890";
int times = [[string componentsSeparatedByString:@"-"] count]-1;
NSLog(@"Counted times: %i", times);
输出:
Counted 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);
【讨论】:
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);
这行得通。希望能帮助到你。快乐编码:)
【讨论】:
int num = [[[myString mutableCopy] autorelease] replaceOccurrencesOfString:@"-" withString:@"X" options:NSLiteralSearch range:NSMakeRange(0, [myString length])];
replaceOccurrencesOfString:withString:options:range: 方法返回已进行替换的数量,因此我们可以使用它来计算您的字符串中有多少 -s。
【讨论】:
autorelease。我已经使用 ARC 这么久了,以至于我忘记了不是每个人都在使用!
你可以使用NSString的replaceOccurrencesOfString:withString:options:range:方法
【讨论】:
如果字符串以您要检查的字符开头或结尾,则当前选择的答案将失败。
改用这个:
int numberOfOccurances = (int)yourString.length - (int)[yourString stringByReplacingOccurrencesOfString:@"-" withString:@""].length;
【讨论】: