ios - 如何查找特定字符在 NSString 中以大写形式出现的次数?

标签 ios objective-c iphone nsstring uppercase

有什么方法可以在 NSString 中找到任何特定字符的大写出现,例如:

NSString *str=@"How many U's are in Uppercase";

我尝试的是给出所有大写字符,

int count=0;  
for (i = 0; i < [str length]; i++) {
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[str characterAtIndex:i]];
    if (isUppercase == YES)
       count++;
}

[[str componentsSeparatedByCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet]] count] - 1;

但我需要在 NSString 中出现任何特定字符的大写。

最佳答案

你可以用正则表达式来做:

NSString *str = @"How many U's are in Uppercase";
NSString *pattern = @"U";
NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
NSArray *result = [expression matchesInString:str options:0 range:NSMakeRange(0, str.length)];
NSLog(@"%ld", result.count); // 2

关于ios - 如何查找特定字符在 NSString 中以大写形式出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39207122/

相关文章:

ios - 将 Firestore DB 与 swift 4.0 一起使用,每次我进行身份验证时,保存到数据库都会创建一个随机字 rune 档

ios - AVAudioPlayer 返回错误的文件持续时间

ios - NSKeyedArchiver 适用于模拟器但不适用于实际设备

ios - apple 是否接受没有新用户注册的 iOS 应用程序?

html - 是否可以使 "HTML to speech"与 "Text to speech"相同?

ios - 为什么不能使用 xcode 将图像导入到 iphone 应用程序的 Assets 目录中?

iphone - 在iPhone桌面上添加图标

iphone - 无法启动音频播放器

iphone - 如果我需要为所有测试人员预先创建一个 Ad Hoc 分发证书和配置,那么 TestFlight App 有什么好处?

IPHONE - 检测指针是否在坐标内