user762034
user762034

Reputation:

Generate string of random characters cocoa?

I know how to generate random numbers, but what I really need is a string of random characters. This is what I have so far:

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789?%$";

    char generated;
    generated = //how do i define this?

    NSLog(@"generated =%c", generated);
    [textField setStringValue:generated];

Upvotes: 2

Views: 1982

Answers (2)

John Riselvato
John Riselvato

Reputation: 12904

-(NSString*)generateRandomString:(int)num {
    NSMutableString* string = [NSMutableString stringWithCapacity:num];
    for (int i = 0; i < num; i++) {
        [string appendFormat:@"%C", (unichar)('a' + arc4random_uniform(25))];
    }
    return string;
}

then Call it like this for a 5 letter string:

NSString* string = [self generateRandomString:5];

Upvotes: 2

Andrew
Andrew

Reputation: 2710

See this SO Q & A.

Generate a random alphanumeric string in Cocoa

Upvotes: 1

Related Questions