我想排序iOS UITableView對象。我目前使用下面的代碼:排序忽略標點符號(Objective-C)
// Sort terms alphabetically, ignoring case
[self.termsList sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
這個排序名單,惠斯特忽略大小寫。但是,忽略標點符號也會很好。例如:
car
c.a.t.
cat
(實際上它並不無論哪兩隻貓(貓或貓)的至上,只要他們進行排序:
c.a.t.
car
cat
應如下排序彼此相鄰)。
有沒有簡單的方法來解決這個問題?我認爲解決方案將涉及從字符串中提取字母數字字符,然後比較這些字符串,然後將它們返回到以前的狀態,並再次包含非字母數字字符。
事實上,我真正關心的唯一字符是句點(。),但是如果有一種方法可以很容易地覆蓋所有標點符號,那麼知道它會很有用。
注:我在一個月前詢問exact same question of Java。現在,我正在Objective-C中創建相同的解決方案。我不知道是否有針對iOS的API,使這個易得什麼花樣......
編輯:我一直在使用下面的代碼剝離標點和填充另一個陣列我排序(由@tiguero建議)嘗試。但是,我不知道如何完成最後一步:按照第二個順序實際排序第一個數組。這裏是我的代碼:
NSMutableArray *arrayWithoutPunctuation = [[NSMutableArray alloc] init];
for (NSString *item in arrayWithPunctuation)
{
// Replace hyphens/periods with spaces
item = [item stringByReplacingOccurrencesOfString:@"-" withString:@" "]; // ...hyphens
item = [item stringByReplacingOccurrencesOfString:@"." withString:@" "]; // ...periods
[arrayWithoutPunctuation addObject:item];
}
[arrayWithoutPunctuation sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
這提供了排序「arrayWithoutPunctuation」,當然不包含標點符號。這是不好的,因爲儘管它現在被很好地排序,但它不再包含對於數組來說至關重要的標點符號。我需要做的是根據'arrayWithoutPunctuation'的順序排序'arrayWithPunctuation'...任何幫助表示讚賞。
只需使用自定義比較器即可。 –
我的回答無效嗎? – tiguero
至今我還沒有能夠實現它。我會接受一次,我可以得到它的工作 – CaptainProg