user5276912
user5276912

Reputation: 121

How do I loop through NSString N number of times?

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

NSString *fl = @"zxcvbn";

Upvotes: 0

Views: 423

Answers (2)

Rob
Rob

Reputation: 438417

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') { ... } 
}

Upvotes: 0

Islam
Islam

Reputation: 3733

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.

Upvotes: 1

Related Questions