Reputation: 167
I'm writing a small app for the iphone and I'm trying to write a function that will insert an NSMutableString into an NSArray in alphabetical order. Also I'll be writing a sort to sort the entire array as well. For both cases I'm wondering what the best way of comparing NSMutableStrings is. Is there a specific function I can use?
Thanks for your help.
Upvotes: 0
Views: 884
Reputation: 3907
For sorting array
NSArray *sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Upvotes: 2
Reputation: 19469
I think this should work for you. This is my answer which I have taken from the link:
SOLUTION-1: I have modified it here a bit to make it more easier for your case:
Let us assume String1 is one NSString.
//Though this is a case sensitive comparison of string
BOOL boolVal = [String1 isEqualToString:@"My Default Text"];
//Here is how you can do case insensitive comparison of string:
NSComparisonResult boolVal = [String1 compare:@"My Default Text" options:NSCaseInsensitiveSearch];
if(boolVal == NSOrderedSame)
{
NSLog(@"Strings are same");
}
else
{
NSLog(@"Strings are Different");
}
Here if boolVal is NSOrderedSame then you can say that strings are same else they are different.
SOLUTION-2: Also you don't find this easy, you can refer to Macmade's answer under the same link.
Hope this helps you.
Upvotes: 2
Reputation: 237010
If you look under "Identifying and comparing strings" in the NSString reference, you'll find several options. They do slightly different things, since you might want to compare strings in different ways (e.g. are numbers compared in lexical or numeric order?). The most basic is compare:
— you can probably start there and choose a more complicated version as needed.
Upvotes: 2
Reputation: 17317
I think you're looking for
(NSComparisonResult)[aString compare: bString];
You can use this or one of the related methods if you're doing insertion sort. However, if you want to do a one time sort of the NSMutableArray, you can use one of the NSMutableArray sorting methods such as sortUsingComparator:
.
Upvotes: 4
Reputation: 35131
Try NSArray
's sortedArrayUsingSelector:
method:
NSArray * stringArray = [NSArray arrayWithObjects:@"dddsss", @"aada", @"bbb", nil];
[stringArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@", [stringArray sortedArrayUsingSelector:@selector(compare:)]);
Out put:
(
aada,
bbb,
dddsss
)
What's more, you can use NSSortDescriptor
to decide ASC or DESC order.
Upvotes: 1