打印文本中符合的符号,没有重复

时间:2013-12-14 22:21:26

标签: ios objective-c cocoa-touch

我几天来一直在努力解决这个问题。真的需要你的帮助和意见。

我们有一个字符串,其中包含一个文本:

NSString *contentOfFile = [[NSString alloc] initWithString:@"This is string#1"];

现在我必须记录符号,这个符号在此字符串中没有重复。结果应如下所示:

whitespace symbol here
#
1
g
h
i
n
r
s
t

我知道使用字符集和迭代器在C代码中解决这个问题非常简单,但我正在寻找在objective-c中处理此操作的同样简单而优雅的方法。

我当时想在字符串上使用NSCharacterSet,但我对objective-c缺乏了解,所以我需要你的帮助。提前感谢所有回复的人。

2 个答案:

答案 0 :(得分:0)

// Create the string
NSString *contentOfFile = @"This is string#1";

// Remove all whitespaces
NSString *whitespaceRemoval = [contentOfFile stringByReplacingOccurrencesOfString:@" " withString:@""];

// Initialize an array to store the characters
NSMutableArray *components = [NSMutableArray array];

// Iterate through the characters and add them to the array
for (int i = 0; i < [whitespaceRemoval length]; i++) {
    NSString *character = [NSString stringWithFormat:@"%c", [whitespaceRemoval characterAtIndex:i]];
    if (![components containsObject:character]) {
        [components addObject:character];
    }
}

答案 1 :(得分:0)

利用NSSet的特征:它的成员是不同的。

NSString *contentOfFile = @"This is string#1";

NSMutableSet *set = [NSMutableSet set];

NSUInteger length = [contentOfFile length];
for (NSUInteger index = 0; index < length; index++)
{
    NSString *substring = [contentOfFile substringWithRange:NSMakeRange(index, 1)];
    [set addObject:substring];
}

NSLog(@"%@", set);

然而,还有一个问题,那就是一组的成员也是无序的。幸运的是,数组是有序的。所以,如果你改变最后一行:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSArray *array = [set sortedArrayUsingDescriptors:@[sortDescriptor]];

NSLog(@"%@", array);

如果不区分大小写对您很重要,那么遗憾的是NSSet没有“不区分大小写”的选项。但是,您可以将源字符串转换为全部小写,如下所示:

NSString *contentOfFile = [@"This is string#1" lowercaseString];

这将为您提供与样本输出完全匹配的结果。