我正在以字符串的形式读取一个包含单词和名称的文件。然后我把它分解成一个字符串数组。我想要做的是打印出也是单词的名字。这些单词的拼写只有小写字母,并且名称的第一个字母大写。因此,我希望对大小写进行相同的排序,以便Ii可以扫描数组并接收副本。
因此,我的main.m文件中的内容现在如下所示:
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *words = [wordString componentsSeparatedByString:@"\n"];它到处都说我应该使用caseIntensiveCompare方法,但是我不明白它是如何工作的,或者在这种特殊情况下如何使用它。当我在谷歌上搜索它时,我得到的结果是:
NSString *aString = @"ABC";
NSString *bString = @"abc";
if ([aString caseInsesitiveCompare: bString]) == NSOrderedSame)
{
//The strings are ordered equal
}这似乎是错误的,首先是因为我只有一个字符串,其次我希望它实际上对它们进行相同的排序,而不是检查它们是否相同。如果有人能给我一点提示怎么做,我将非常感谢!提前感谢// Bjoern
发布于 2013-11-11 21:22:31
我不确定我是否正确理解了你的问题。但我所理解的是,你需要首先在可变集合中存储数组字符串,然后在此基础上,你可以将现有的数组字符串与新的数组字符串进行比较,如下面的代码所示。因此,您可以过滤数组并识别重复单词和名称。下面假设单词是包含字符串值的数组。所以在此基础上处理进一步的代码。
NSMutableSet* existing = [NSMutableSet set];
NSMutableArray* newArray = [NSMutableArray
array];
for (id object in words) {
if (![existing containsObject:[[object
name]lowercaseString]) {
[existing addObject:[[object
name]lowercaseString];
[newArray addObject:object];
}
else
{
NSLog(@"duplicate name=%@", [object name]);
}
}发布于 2013-11-12 05:17:15
你可以尝试这样做(在评论中解释):
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
// Get all the words by separating on newlines & convert to lowercase
// Note: Assuming that the list doesn't contain duplicate strings
// (i.e. the same word or name twice)
// If it does, you should separate/add_to_set/get_all_objects/lowercase instead
NSArray *words = [[wordString componentsSeparatedByString:@"\n"]
valueForKey:@"lowercaseString"];
// Create a counted set to keep track of duplicate strings
NSCountedSet *bag = [[NSCountedSet alloc] initWithArray:words];
// Create a mutable set to add only duplicates
NSMutableSet *duplicates = [NSMutableSet setWithCapacity:0];
// Iterate and add words that appear more than once in the counted set
for (NSString *word in bag) {
if ([bag countForObject:word] > 1) {
[duplicates addObject:word];
}
}
NSLog(@"Words: %lu | Unique words: %lu | Duplicates: %lu", words.count, bag.count, duplicates.count);
// Output => Words: 235887 | Unique words: 234372 | Duplicates: 1515
}
}现在,duplicates是一组既是单词又是名称的字符串(根据您的要求,即它们只是大小写不同)。您可以通过发送[duplicates allObjects]来获取单词数组。
https://stackoverflow.com/questions/19903387
复制相似问题