2

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];
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • Note that `char generated;` declares a variable holding *one* character, not an array of characters. Also, `setStringValue:` takes a pointer to an NSString object, not a C string. – Peter Hosey Jul 01 '11 at 03:56
  • Do you want to generate a string of any random characters, including unprintables, or only characters in the `letters` string? – Peter Hosey Jul 01 '11 at 03:56
  • Only characters in the letters string –  Jul 01 '11 at 03:58
  • Oh I see because a char data type holds only a single character. Yes so I got it working with NSMutableString. Thanks for the tips. Also the book you recommended is great! –  Jul 01 '11 at 05:21

2 Answers2

2
-(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];
John Riselvato
  • 12,854
  • 5
  • 62
  • 89
1

See this SO Q & A.

Generate a random alphanumeric string in Cocoa

Community
  • 1
  • 1
Andrew
  • 2,690
  • 23
  • 27