0

how do I loop the string 9 times ? (z x c v b n z x c)

NSString *fl = @"zxcvbn";
Rob
  • 415,655
  • 72
  • 787
  • 1,044
user5276912
  • 131
  • 1
  • 1
  • 8
  • Can you be more specific? Do you need to go through the characters and if there's less characters then the loop count start appending string to the end from the beginning? – Islam Nov 22 '15 at 04:28
  • no need for appending just stop tat that count – user5276912 Nov 22 '15 at 04:33

2 Answers2

1

Here's a fast and dirty snippet:

NSString *string = @"abcdef";
NSString *letter = nil;
int n = 9;
for (int index = 0; index < n; index++) {
    // start over if it's more than the length
    int currentIndex = index % string.length;

    letter = [string substringWithRange:NSMakeRange(currentIndex, 1)];

    NSLog(@"letter: %@", letter);
}

If you want a low-level example with detailed explanation check this out.

Community
  • 1
  • 1
Islam
  • 3,654
  • 3
  • 30
  • 40
0

In addition to using substringWithRange (which returns a NSString), you can also use characterAtIndex to get the character value:

NSInteger n = 9;

for (NSInteger index = 0; index < n; index++) {
    unichar character = [fl characterAtIndex:index % fl.length];

    // do something with `character`, e.g.
    //
    // if (character == 'z') { ... } 
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044