- // main.m
- // 找出两个字字符串的的相同部分
- //
- // Created by Mengjiechen on 4/7/16.
- // Copyright © 2016 Mengjiechen. All rights reserved.
- //有什么方式可以最快找出2个字符串相同的元素,且找出的相同元素不重复
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- NSString *s1 = @"aabbccdef";
- NSString *s2 = @"sad hellojsad";
- NSMutableSet *arr1 = [NSMutableSet set];
- NSMutableSet *arr2 = [NSMutableSet set];
- //第一个字符串去掉重复
- for (int i = 0; i < s1.length; i++) {
- unichar c = [s1 characterAtIndex:i];
- NSNumber *temp = [NSNumber numberWithChar:c];
- [arr1 addObject:temp];
-
- }
- //重新组成字符串
- NSMutableString *mstr1 = [NSMutableString string];
- for (NSNumber *d in arr1) {
- unichar temp = [d charValue];
- [mstr1 appendFormat:@"%c",temp];
- }
-
- //第二个字符串去掉重复
- for (int i = 0; i < s2.length; i++) {
- unichar c = [s2 characterAtIndex:i];
- NSNumber *temp = [NSNumber numberWithChar:c];
- [arr2 addObject:temp];
-
- }
- //重新组成字符串
- NSMutableString *mstr2 = [NSMutableString string];
- for (NSNumber *d in arr2) {
- unichar temp = [d charValue];
- [mstr2 appendFormat:@"%c",temp];
- }
-
- NSLog(@"%@",mstr1);
- printf("----------------------\n");
- NSLog(@"%@",mstr2);
- NSMutableString *result = [NSMutableString string];
- //查找重复相同部分字符
- [mstr1 enumerateSubstringsInRange:NSMakeRange(0, mstr1.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
- NSRange temp = [mstr2 rangeOfString:substring];
- if (temp.location != NSNotFound) {
- [result appendString:substring];
- }
- }];
-
- NSLog(@"%@",result);
-
- }
- return 0;
- }
复制代码
运行结果:2016-04-07 13:09:09.261 找出两个字字符串的的相同部分[743:158657] beadcf
----------------------
2016-04-07 13:09:09.262 找出两个字字符串的的相同部分[743:158657] hdea sojl
2016-04-07 13:09:09.262 找出两个字字符串的的相同部分[743:158657] ead
Program ended with exit code: 0 |