Question

How can I count the number of different characters used in a NSString. Basically, from the string

Condimentum Consectetur Cras

I would like to get 14 as an answer because:

Condimet scura

We can't assume the NSString's content will always be English; a behaviour similar to [NSString length] for such cases - counting Unicode characters - is, therefore, expected.

Was it helpful?

Solution

NSString *oldString=@"THIS IS OLD STRING.";
NSMutableArray *charArray=[[[NSMutableArray alloc]init ] autorelease];
for (int k1=0; k1<[oldString length]; k1++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [oldString characterAtIndex:k1]];
    if (![charArray containsObject:ichar]) {
        [charArray addObject:ichar];
    }
}
NSMutableString *newString=[[NSMutableString alloc]init]; 
for (int k2=0; k2<[charArray count]; k2++) {
    NSString *ichar  =[charArray objectAtIndex:k2];
    [newString appendString:ichar];
}
    NSLog(@"old string lenght is %d",[oldString length]);
NSLog(@"new string lenght is %d",[newString length]);

Did You try this. I hope it will helps You.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top