2013-12-14 35 views
0

我一直在努力解決這個問題幾天了。真的需要你的幫助和意見。打印符號,在文本中遇到,沒有重複

我們有一個字符串,保存文本:

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的知識,所以我需要你的幫助。預先感謝所有回覆的人。

+0

缺乏瞭解並不意味着您無法閱讀'<該語言庫>的文檔。 [提示](https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSMutableCharacterSet_Class/Reference/Reference.html#//apple_ref/doc/uid/20000158-addCharactersInString_)。 – 2013-12-14 22:25:43

+0

感謝您的提示! – Soberman

+0

該鏈接指向'NSMutableCharacterSet'的'addCharactersInString:'方法的文檔。有了這個,你的問題可以在一個LOC中解決。 – 2013-12-14 22:28:33

回答

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]; 

,這會給你的結果你的樣品輸出精確匹配。

+0

非常感謝您的回答,這正是我需要的。因爲我無法打印它,所以比NSMutableCharacterSet更好。再次感謝你。 – Soberman

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]; 
    } 
} 
+0

謝謝你的迴應。但是在你的例子中會出現重複字符,而我只需要獲取一次字符,不需要複製 – Soberman

+0

然後在添加對象之前只需添加一個檢查來查看數組是否包含對象。看到我更新的答案。 –