/**
在一个字符串中找到第一个只出现一次的字符
示例:
@“abcdeffggab”
输出 @“c”
*/
+ (void)findFirstString {
NSString *str = @"abcdeffggab";
NSLog(@"输入字符:%@",str);
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (int i = 0; i < str.length; i++) {
NSString *key = [NSString stringWithFormat:@"%c",[str characterAtIndex:i]];
if ([dic objectForKey:key]) {
int num = [[dic objectForKey:key] intValue];
NSString *value = [NSString stringWithFormat:@"%d",++num];
[dic setObject:value forKey:key];
}else {
[dic setObject:[NSString stringWithFormat:@"1"] forKey:key];
}
}
for (int i = 0; i < str.length; i++) {
NSString *key = [NSString stringWithFormat:@"%c",[str characterAtIndex:i]];
if ([[dic objectForKey:key] isEqualToString:@"1"]) {
NSLog(@"输出字符:%@",key);
break;
}
}
}
运行: