gpt4 book ai didi

objective-c - 从数组中获取特定长度的字符串

转载 作者:行者123 更新时间:2023-12-03 17:32:23 24 4
gpt4 key购买 nike

我有这段代码可以在文本文件中读取,单词之间用换行符分隔。我想要做的是将所有单词读入一个数组,然后从该数组中选取所有六个字母的单词。

我有下面的代码,但它似乎在 for 循环内生成错误。

另外,读入文本文件后,是否需要释放它?

NSString* path = [[NSBundle mainBundle] pathForResource:@"newdict" ofType:@"txt"];

NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

NSArray* allLinedStrings = [content componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];

int wordcount = [allLinedStrings count];
int i;
NSMutableArray* sixLetterWords;

for( i = 0 ; i < wordcount ; i++)
{
NSString* word = [allLinedStrings objectAtIndex: i];
if (StrLength(word) == 6)
[sixLetterWords addObject:word];
}

最佳答案

比 for 循环更好的选择是 fast enumeration :

// Don't forget to actually create the mutable array
NSMutableArray * sixLetterWords = [[NSMutableArray alloc] init];
for( NSString * word in allLinedStrings ){
if( [word length] == 6 ) [sixLetterWords addObject:word];
}

blocks-based enumerationenumerateObjectsUsingBlock: :

NSMutableArray * sixLetterWords = [[NSMutableArray alloc] init];
[allLinedStrings enumerateObjectsUsingBlock:^(id word, NSUInteger idx, BOOL * stop){
if( [(NSString *)word length] == 6 ) [sixLetterWords addObject:word];
}];

还有可能filter the array :

NSArray * sixLetterWords = [allLinedStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length == 6"

请注意,最后一个选项为您提供了一个自动释放的数组——如果您想保留它,则必须保留它。有了这些,您就不再需要担心数组长度或显式索引;它由数组为您处理。 Fast enumeration正如其名称所示,它也比普通的 for 循环更快

用于将文本文件读入字符串的方法 stringWithContentsOfFile:encoding:error: 不是 newalloc ,也不以 copymutableCopy 开头;因此,根据Cocoa memory management rules ,您不拥有它,也不必释放它。 (如果您希望它保留在当前方法的末尾之后,则需要保留它。)

关于objective-c - 从数组中获取特定长度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com