Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray with capital letters

I have an NSArray that looks like this:

contactNamesArray = [[NSMutableArray alloc] initWithObjects:@"John Galt", @"Michael Wales", @"James Joyce", @"Shakespeare", nil];

From it, I want to make an NSArray that would have all the same values, but that would look like this:

newContactNamesArray = [[NSMutableArray alloc] initWithObjects:@"john galt", @"michael wales", @"james joyce", @"shakespeare", nil];

I want to do this because I want to make a search in that second array and I want to replace every capital letter in it with a normal letter.

How do you do something like this in Objective-C? Thanks in advance!

like image 591
Sergey Grischyov Avatar asked May 28 '26 23:05

Sergey Grischyov


2 Answers

You can go through an array, and convert every element to lower case by calling

[element lowercaseString]

on it. However, this is grossly suboptimal for implementing case-insensitive search: a better approach would be keeping strings as-is, and employ caseInsensitiveCompare method for your search instead.

like image 179
Sergey Kalinichenko Avatar answered May 30 '26 13:05

Sergey Kalinichenko


Why are you making a copy? You can sort an NSArray in a case insensitive way:

NSArray *sortedContactNamesArray = [contactNamesArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

Also, bear in mind that sortedArrayUsingSelector returns an array with references to the original items, not copies of them.

like image 44
Daniel Martín Avatar answered May 30 '26 15:05

Daniel Martín



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!