I’m trying to write a method that generates all substrings of a given NSString with a fixed length, but I’m getting stuck. Here’s the idea of what I want:
-(int)countGoodSubstringsOfString:(NSString*)str ofLength:(int)len {
int cnt = 0;
for (NSString *substr substring of str of length len) {
if ([self isGoodSubstring:substr ofString:str])
cnt++;
}
return cnt;
}
By substring, I mean all possible combinations of len characters from str. If str = @"ABCDE" and len = 4, then I need to get 5 substrings: @"ABCD", @"ABCE", @"ABDE", @"ACDE", @"BCDE".
If len were fixed, then I could just write nested for loops to get all the substrings like this
NSString *substr = @"";
for (int i=0; i<str.length-len+1; ++i) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(i,1)]];
for (int j=i+1; j<str.length-len+2; ++j) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(j,1)]];
...
for(int k=j+1; k<str.length; ++k) {
substr = [substr stringByAppendingString:[str substringWithRange:NSMakeRange(k,1)]];
if ([self isGoodSubstring:substr ofString:str])
cnt++;
But since len is part of the input, I can’t know it in advance. How can I get around this problem?
EDIT: I finally managed to find the solution. It uses same ideas as yours, but it’s recursive, so you don’t have to know the length.
Initial call should look something like this: