
Objective-C实现单词计数(附完整源码)
发布日期:2025-04-25 15:19:20
浏览次数:2
分类:精选文章
本文共 1977 字,大约阅读时间需要 6 分钟。
Objective-C 单词计数器
创建一个新的 Xcode 项目
在 Xcode 中创建一个新的项目是实现 Objective-C 单词计数器的第一步。选择 “Create a new Xcode project”,然后选择 “macOS” 下的 “Command Line Tool”。输入项目名称,比如 “WordCounter”。
在 main.m 文件中编写代码
在项目创建完成后,打开 main.m
文件,编写以下代码:
#import@interface WordCounter : NSObject- (int)countWordsInString:(NSString *)string;- (void)countWords:(NSString *)string inDocument:(NSURL *)documentURL;@end
#import@interface WordCounter : NSObject- (int)countWordsInString:(NSString *)string;- (void)countWords:(NSString *)string inDocument:(NSURL *)documentURL;@end@implementation WordCounter- (int)countWordsInString:(NSString *)string { NSRegularExpression *wordPattern = [NSRegularExpression regularExpression:@"\\b\\w+\\b"]; NSArray *matches = [wordPattern matchesInString:string options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotAll | NSRegularExpressionWordBoundaryOnly]; return matches.count;}- (void)countWords:(NSString *)string inDocument:(NSURL *)documentURL { NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:documentURL]; if (!fileHandle) { NSLog(@"无法打开文件"); return; } NSString *contents = [fileHandle readContents]; int wordCount = [self countWordsInString:contents]; printf("单词数:%d\n", wordCount);}@end
使用示例
在 main
函数中添加以下代码:
int main(int argc, const char *argv) { @autoreleasepool { NSString *inputFile = [NSString stringWithUTF8String: argv[1]]; NSURL *documentURL = [NSURL fileURLWithPath: inputFile]; WordCounter *wordCounter = [[WordCounter alloc] init]; [wordCounter countWords: [documentURL path] inDocument: documentURL]; } return 0;}
运行项目
在 Xcode 中运行项目,选择你的 main.m
文件作为目标,点击运行按钮。程序会提示你选择一个文本文件,计算其中的单词数量。
项目结构
你的项目结构应该包含以下文件:
main.m
— 你的主程序文件main.xcodeproj
— Xcode 项目文件WordCounter.h
和 WordCounter.m
— 你的 Objective-C 类文件总结
通过以上步骤,你已经成功创建并运行了一个 Objective-C 单词计数器程序。你可以根据需要修改代码,添加更多功能或调整算法。
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月02日 16时17分18秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!