我正在读取包含单词和名称的文件,作为字符串。然后我把它分成一个字符串数组。我想要做的是打印出也是文字的名字。单词拼写只有小写字母,名称有首字母。因此,我想命令大小写相同,以便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方法,但我不明白它是如何工作的,或者在这种特殊情况下如何使用它...当我在google上搜索它时我得到的是:
NSString *aString = @"ABC";
NSString *bString = @"abc";
if ([aString caseInsesitiveCompare: bString]) == NSOrderedSame)
{
//The strings are ordered equal
}
这似乎是错误的,首先是因为我只有一个字符串,其次我希望它实际上将字母命名为相同,而不是检查它们是否被订购相同。 如果有人能给我一些如何做到这一点,我会非常感激! 在此先感谢// Bjoern
答案 0 :(得分:0)
不确定我是否正确理解了您的问题。但是我理解的是你需要首先在可变集中存储数组字符串,然后根据你可以比较现有的数组和新的数组字符串代表下面的代码。这样你可以过滤你的数组,并识别重复的单词和名称。下面假设单词是包含字符串值的数组。所以在处理进一步代码的基础上。
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]);
}
}
答案 1 :(得分:0)
您可以尝试这样的事情(评论中的解释):
#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
是一组字符串,它们都是单词&amp;名称(根据您的要求,即它们仅在大小写方面有所不同)。您可以通过发送[duplicates allObjects]
来获取一系列单词。