Last active
November 11, 2016 23:50
-
-
Save hbhargava7/9ef542ce0d893ae93427bb2dd0535251 to your computer and use it in GitHub Desktop.
NSString extension to generate a random alphanumeric string of length n.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Created by Hersh Bhargava of H2 Micro (www.h2micro.com) */ | |
@interface NSString (Randomize) | |
+ (NSString *)randomStringWithLength:(int)length; | |
@end | |
@implementation NSString (Randomize) | |
+ (NSString *)randomStringWithLength:(int)length | |
{ | |
NSString *alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789"; | |
NSMutableString *s = [NSMutableString stringWithCapacity:length]; | |
for (NSUInteger i = 0U; i < length; i++) { | |
u_int32_t r = arc4random() % [alphabet length]; | |
unichar c = [alphabet characterAtIndex:r]; | |
[s appendFormat:@"%C", c]; | |
} | |
return s; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment