我试图在NSString中重复使用他们的计数字符。
例如,setupsetpreset作为输入,它返回' set'以及计数3.
让我用另一个例子来解释。
输入1: upsetpreset
预期输出1:设置2
输入2: qwertygdgpopgdg
预期输出2: gdg 2
答案 0 :(得分:2)
请参阅下文
NSString *string = @"This is a test. This is only a test.";
NSCountedSet *countedSet = [NSCountedSet new];
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByWords | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
// This block is called once for each word in the string.
[countedSet addObject:substring];
// If you want to ignore case, so that "this" and "This"
// are counted the same, use this line instead to convert
// each word to lowercase first:
// [countedSet addObject:[substring lowercaseString]];
}];
NSLog(@"%@", countedSet);
结果:
“这个” - 2 “是” - 2 “a2 “测试” - 2 “只” - 1
答案 1 :(得分:1)
在获得大量自定义逻辑以获取非空格字符串中的常用字符后,我得到了解决方案: -
NSString *string=@"setupsetpreset";
string=@"sheraheshehehesheshe";
NSMutableArray *a=[[NSMutableArray alloc] init];
NSMutableArray *b=[[NSMutableArray alloc] init];
for (int i=0; i<(string.length); i++) {
[a addObject:[NSString stringWithFormat:@"%c",[string characterAtIndex:i]]];
}
NSCountedSet *countedSet = [NSCountedSet new];
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
[countedSet addObject:substring];
}];
NSMutableArray *c=[[NSMutableArray alloc] init];
for (int i=0; i<(string.length); i++) {
if([countedSet countForObject:[a objectAtIndex:i]]>=2){
if(![b containsObject:[a objectAtIndex:i]]){
[c addObject:[NSString stringWithFormat:@"%d",(int)[countedSet countForObject:[a objectAtIndex:i]]]];
}
[b addObject:[a objectAtIndex:i]];
}
}
int total=0;
for (NSString *s in c){
int m=[s intValue];
total+=m;
}
total=total/c.count;
NSString *s=[b componentsJoinedByString:@""];
[c removeAllObjects];
for (int i=0; i<(s.length); i++) {
if([countedSet countForObject:[b objectAtIndex:i]]>=total){
[c addObject:[b objectAtIndex:i]];
}
}
s=[c componentsJoinedByString:@""];
int iterate=0;
NSString *substring;
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
while (iterate<s.length-total) {
NSString *searchstring=[s substringWithRange:NSMakeRange(iterate, total)];
if ([string rangeOfString:searchstring].location == NSNotFound) {
} else {
[dict setObject:[NSNumber numberWithInt:[[dict objectForKey:searchstring] intValue]+1] forKey:searchstring];
}
iterate++;
}
[a removeAllObjects];
[b removeAllObjects];
a=[dict.allValues mutableCopy];
b=[dict.allKeys mutableCopy];
int max = [[a valueForKeyPath:@"@max.intValue"] intValue];
NSInteger Aindex = [a indexOfObject:[NSNumber numberWithInt:max]];
substring =[NSString stringWithFormat:@"%@",[b objectAtIndex:Aindex]];
NSLog(@"Substring %@ is repeated %d times",substring,max);
希望它有助于满足某人的需求:)感谢Kiran为我提供了一组逻辑,这些逻辑是您的查询所必需的部分和Ruchira。